当前位置:网站首页>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+";");
}
}
}
边栏推荐
- 消息订阅与发布
- 28: Chapter 3: develop Passport Service: 11: define attributes in the configuration file, and then obtain them in the code;
- How to promote the progress of project collaboration | community essay solicitation
- Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
- Qt学习21 Qt 中的标准对话框(下)
- Golang — template
- NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
- 金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])
- 树的深入和广度优先遍历(不考虑二叉树)
- UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
猜你喜欢
[développement technologique - 24]: caractéristiques des technologies de communication Internet des objets existantes
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
消息订阅与发布
RocksDB LRUCache
QT learning 24 layout manager (III)
jvm-运行时数据区
Spring cup eight school league
Flutter dynamic | fair 2.5.0 new version features
Golang - command line tool Cobra
随机推荐
Richview trvstyle liststyle list style (bullet number)
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
消息订阅与发布
Golang — template
jvm-类加载
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
叶酸修饰的金属-有机骨架(ZIF-8)载黄芩苷|金属有机骨架复合磁性材料([email protected])|制备路线
全局事件总线
Golang — template
金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])
[技术发展-24]:现有物联网通信技术特点
JVM family - overview, program counter day1-1
Global event bus
[combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)
[ACNOI2022]猜数
树的深入和广度优先遍历(不考虑二叉树)
1px problem of mobile terminal
QT learning 21 standard dialog box in QT (Part 2)
Example analysis of QT learning 18 login dialog box
Cross linked cyclodextrin metal organic framework loaded methotrexate slow-release particles | metal organic porous material uio-66 loaded with flavonoid glycosides | Qiyue