当前位置:网站首页>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+";");
}
}
}
边栏推荐
- Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
- Implementation of Muduo asynchronous logging
- Golang — 命令行工具cobra
- Flutter dynamic | fair 2.5.0 new version features
- Unity embeddedbrowser browser plug-in event communication
- jvm-对象生命周期
- C language standard IO function sorting
- Windos creates Cordova prompt because running scripts is prohibited on this system
- jvm-类加载
- QT learning 17 dialog box and its types
猜你喜欢
[développement technologique - 24]: caractéristiques des technologies de communication Internet des objets existantes
Message subscription and publishing
Failure of vector insertion element iterator in STL
FPGA测试方法以Mentor工具为例
如何使用lxml判断网站公告是否更新
[email protected])|制备路线"/>
叶酸修饰的金属-有机骨架(ZIF-8)载黄芩苷|金属有机骨架复合磁性材料([email protected])|制备路线
The solution of Chinese font garbled code in keil5
Summary of common error reporting problems and positioning methods of thrift
Qt学习22 布局管理器(一)
Qt学习25 布局管理器(四)
随机推荐
Conversion function and explicit
[ACNOI2022]猜数
[technology development-24]: characteristics of existing IOT communication technology
Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
3D vision - 2 Introduction to pose estimation - openpose includes installation, compilation and use (single frame, real-time video)
Similarities and differences of sessionstorage, localstorage and cookies
Spring cup eight school league
Dlopen() implements dynamic loading of third-party libraries
Current situation, analysis and prediction of information and innovation industry
Vite project commissioning
Golang — template
SQL Injection (GET/Search)
树的深入和广度优先遍历(不考虑二叉树)
Formation of mil-100 (FE) coated small molecule aspirin [email protected] (FE) | glycyrrhetinic acid modified metal organ
QT learning 19 standard dialog box in QT (top)
Installation impression notes
Use and design of Muduo buffer class
Implementation of Muduo accept connection, disconnection and sending data
Global event bus
Failure of vector insertion element iterator in STL