当前位置:网站首页>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+";");
}
}
}
边栏推荐
- Golang — template
- windos 创建cordova 提示 因为在此系统上禁止运行脚本
- Field problems in MySQL
- QT learning 20 standard dialog box in QT (middle)
- [ACNOI2022]猜数
- Mysql:insert date:sql error [1292] [22001]: data truncation: incorrect date value:
- Metal organic framework material zif-8 containing curcumin( [email protected] Nanoparticles) | nano metal organic framework carry
- JS new challenges
- 树的深入和广度优先遍历(不考虑二叉树)
- 从零开始的基于百度大脑EasyData的多人协同数据标注
猜你喜欢

金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)

Go language unit test 4: go language uses gomonkey to test functions or methods

从零开始的基于百度大脑EasyData的多人协同数据标注

挡不住了,国产芯片再度突进,部分环节已进到4nm

Bidirectional linked list (we only need to pay attention to insert and delete functions)

The solution of Chinese font garbled code in keil5

QT learning 21 standard dialog box in QT (Part 2)

Qt学习19 Qt 中的标准对话框(上)

NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon

Metal organic framework MOFs loaded with non steroidal anti-inflammatory drugs | zif-8 wrapped Prussian blue loaded quercetin (preparation method)
随机推荐
Qt学习22 布局管理器(一)
Uniapp tips - set background music
Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
信创产业现状、分析与预测
金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
Unity embeddedbrowser browser plug-in event communication
FPGA test method takes mentor tool as an example
[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
记录关于银行回调post请求405 问题
QT learning 24 layout manager (III)
金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])
全局事件总线
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
QT learning 17 dialog box and its types
Selenium browser (1)
挡不住了,国产芯片再度突进,部分环节已进到4nm
Uio-66-cooh loaded bendamostine | hydroxyapatite (HA) coated MIL-53 (FE) nanoparticles | baicalin loaded manganese based metal organic skeleton material
Logback log sorting
Qt学习25 布局管理器(四)
QT learning 22 layout manager (I)