当前位置:网站首页>Reflection -- basic usage
Reflection -- basic usage
2022-07-03 14:03:00 【A ke】
because servlet No main method , Other procedures must be used ,tomcat
The static Cannot call directly , want new First generate the object of the class Through object call Non static methods
Any programming language There are traversal subdirectories and sub files ( route ) The ability of
tomcat I do not know! class Your name cannot pass new To get instances
Reflection : adopt java The code gets all the information of the class ( What the human eye can see ), Get the object of the class
Class information : annotation , attribute , Method , Construction method , Attribute types , Attribute name , Attributes decorate ( Public and private ), Method type , Method name , Input quantity , Input parameter type , Enter the name .....
( a key ) How to get information
1. object .getclass
2. class .forName() Class path Call static methods forName Get the corresponding Class object .
tomcat adopt Reflection of the path The other two roads are impassable
3. class .class
calss x1=Person.class; //x1 obtain Person Class information class x2=Cat.class; //x2 obtain Cat Class information class x3=class.forName("Dog Path to class ");
Class information .newlnstance Get an instance of the class . take forName And newlnstance Use in conjunction with , You can create an object based on the class name stored in the string
Must recite v
getFields、 Returns the public Domain ( attribute )
getMethods Return the method of the class
getConstructors Constructor array of class ,
printConstructors(Classcl) Printing construction method
printMethods(Class) Printing method
printFields(Classcl) Print properties ( Domain )
intgetModifiers() Returns a description of the constructor 、 The integer value of the modifier of a method or field . Use Modifier The method in the class can analyze the return value .
Field[ ]getFields()1
•Filed[ ]getDeclaredFie1ds()
getFields Method will return a containing Field An array of objects , These objects record the public domain of this class or its superclass .getDeclaredField Method will also return containing Field An array of objects , These objects record all fields of this class . If there are no fields in the class , perhaps Class Object describes a basic type or array type , These methods will return a length of 0 Array of .
•Method[] getMethods()
•Method[] getDeclareMethods()
Return contains Method An array of objects :getMethods All public methods will be returned , Including public methods inherited from superclasses ;getDeclaredMethods Return all the methods of this class or interface , But it does not include methods inherited by superclasses .
•Constructor[ ] getConstructors()
•Constructor[ ] getDeclaredConstructors()
Return contains Constructor An array of objects , Which includes Class All public constructors of the class described by the object (getConstructors) Or all constructors (getDeclaredConstructors).
•Class getDeclaringClass()
Returns a constructor that describes the definition in the class 、 Method or domain Class object .
•Class[ ] getExceptionTypes() ( stay Constructor and Method Class )
Returns a that describes the type of exception thrown by the method Class An array of objects .
•int getModifiers()
Returns a description of the constructor 、 The integer value of the modifier of a method or field . Use Modifier The method in the class can analyze the return value .
•String getName()
Returns a description of the constructor 、 Method or domain name string .
•Class[ ] getParameterTypes() ( stay Constructor and Method Class )
Returns a... That describes the parameter type Class An array of objects .
•Class getReturnType()( stay Method Class ) To return a description of H Type of Class object .
Use cases :
package com.qcby;
import java.lang.reflect.*;
public class ReflectionTest {
public static void main(String[] args) {
try{
Class cl=Class.forName("com.qcby.Person");
Class supercl=cl.getSuperclass();
String modifiers=Modifier.toString(cl.getModifiers());
if(modifiers.length()>0) System.out.print(modifiers+"");
System.out.print("class"+"com.qcby.Person");
if(supercl !=null&&supercl!=Object.class)System.out.print("extends"+supercl.getName());
System.out.print("\n{\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
}catch(ClassNotFoundException e){
e.printStackTrace();
}System.exit(0);
}
public static void printConstructors(Class cl){
Constructor[] constructors=cl.getDeclaredConstructors();
for(Constructor c:constructors){
String name=c.getName();
System.out.print("");
String modifiers=Modifier.toString(c.getModifiers());
if(modifiers.length()>0) System.out.print(modifiers+"");
System.out.print(name+"(");
Class[] paramTypes=c.getParameterTypes();
for(int j=0;j<paramTypes.length;j++){
if(j>0)System.out.print(",");
System.out.print(paramTypes[j].getName());
}System.out.println(");");
}
}
public static void printMethods(Class cl){
Method[] methods=cl.getDeclaredMethods();
for(Method m:methods){
Class retType= m.getReturnType();
String name=m.getName();
System.out.print("");
String modifiers=Modifier.toString(m.getModifiers());
if(modifiers.length()>0)System.out.print(modifiers+"");
System.out.print(retType.getName()+""+name+"(");
Class[] paramTypes=m.getParameterTypes();
for(int j=0;j<paramTypes.length;j++){
if(j>0) System.out.print(",");
System.out.print(paramTypes[j].getName());
}System.out.println(");");
}
}
public static void printFields(Class cl){
Field[] fields=cl.getDeclaredFields();
for(Field f:fields){
Class type=f.getType();
String name=f.getName();
System.out.print("");
String modifiers=Modifier.toString(f.getModifiers());
if(modifiers.length()>0)System.out.print(modifiers+"");
System.out.println(type.getName()+""+name+";");
}
}
}
边栏推荐
- 【吉林大学】考研初试复试资料分享
- Go language web development series 30: gin: grouping by version for routing
- Golang — template
- 记录关于银行回调post请求405 问题
- Collection of mobile adaptation related articles
- FPGA test method takes mentor tool as an example
- 信创产业现状、分析与预测
- Implementation of Muduo asynchronous logging
- JS continues to explore...
- Bidirectional linked list (we only need to pay attention to insert and delete functions)
猜你喜欢

QT learning 17 dialog box and its types

Uio-66-cooh loaded bendamostine | hydroxyapatite (HA) coated MIL-53 (FE) nanoparticles | baicalin loaded manganese based metal organic skeleton material

MySQL 数据处理值增删改

JVM family - overview, program counter day1-1

Common network state detection and analysis tools

Go language web development series 27: Gin framework: using gin swagger to implement interface documents

Flutter dynamic | fair 2.5.0 new version features

Ocean CMS vulnerability - search php

MySQL data processing value addition, deletion and modification
![Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:](/img/2f/33504391a661ecb63d42d75acf3a37.png)
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
随机推荐
jvm-运行时数据区
PHP maze game
JS download files through URL links
Use vscode to view hex or UTF-8 codes
Dlopen() implements dynamic loading of third-party libraries
RichView TRVStyle ListStyle 列表样式(项目符号编号)
Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
Qt学习20 Qt 中的标准对话框(中)
Depth and breadth first traversal of tree (regardless of binary tree)
Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
Software testing is so hard to find, only outsourcing offers, should I go?
Uniapp tips - scrolling components
使用vscode查看Hex或UTF-8编码
jvm-类加载
SQL Injection (AJAX/JSON/jQuery)
Static linked list (subscript of array instead of pointer)
Metal organic framework (MOFs) antitumor drug carrier | pcn-223 loaded with metronidazole | uio-66 loaded with ciprofloxacin hydrochloride(
C language standard IO function sorting
Flutter dynamic | fair 2.5.0 new version features
挡不住了,国产芯片再度突进,部分环节已进到4nm