Objective:
Recently, the company is doing business component process, where the implementation of the route to the Java reflection mechanism, since used to think of a good study summed up, in fact, whether before the Eventbus 2.x version or retrofit, The early view annotation framework is more or less used in the Java reflection mechanism.
What is the Java reflection mechanism?
Java reflection mechanism is in the running state, for any class, can know all the properties and methods of the class, for any object, can call any one of its methods, this dynamically acquired and dynamically invoke the method of the object called the Java reflection mechanism.
What functions does the reflection mechanism provide?
- To determine the class that any object belongs to at run time
- Constructs an object of any class at run time;
- Determining the member variables and methods of any class at run time;
- A method that invokes any object at run time;
- Generate dynamic proxy;
Java Reflection mechanism classes:
Java.lang.Class; Class
java.lang.reflect.constructor;//Constructor method
Java.lang.reflect.Field//class member variable
java.lang.reflect.Method ;//class method
java.lang.reflect.modifier;//access rights
Java Reflection Mechanism implementation:
1.) Class object acquisition
The first way is to getclass the method person by Object
= new Person ();
class<?> Class1 = Person.getclass ();
The second way is to
Class1 = Person.class by class attribute;
try {
//third means to implement
Class1 = Class.forName ("Com.whoislcj.reflectdemo.Person") through the static method--forname () of class classes;
catch (ClassNotFoundException e) {
e.printstacktrace ();
}
2.) Get summary information for class object
Boolean isprimitive = Class1.isprimitive ();//Judge whether it is the underlying type
boolean IsArray = Class1.isarray ();//Judge whether it is a collection class
Boolean Isannotation = Class1.isannotation ()//Whether it is the annotation class
Boolean isinterface = Class1.isinterface ();//To determine whether it is an interface class
Boolean isenum = Class1.isenum ();//To determine whether it is an enumeration class
Boolean isanonymousclass = Class1.isanonymousclass ();//To determine whether an anonymous inner class
Boolean isannotationpresent = Class1.isannotationpresent (Deprecated.class);//To determine whether or not to be decorated
by an annotation class String className = Class1.getname ()//Get class name contains package name path
Package apackage = Class1.getpackage ();//Get package information
for class String simplename = Class1.getsimplename ()//Fetch class class name
int modifiers = class1.getmodifiers ()//Get Class access rights
class<?>[] declaredclasses = class1.getdeclaredclasses ()//inner class
class<?> Declaringclass = Class1.getdeclaringclass ();//External class
3.) Get properties, methods, constructors, etc. of class object
field[] AllFields = Class1.getdeclaredfields ()//Get all the attributes of the class object field[] Publicfields = Class1.getfields (); Gets the public property of the class object try {field Agefield = Class1.getdeclaredfield ("Age");/Get class specifies the property Field Desfield = Class1.getfiel
D ("des"),//Gets the public attribute specified by class, catch (Nosuchfieldexception e) {e.printstacktrace ();} Method[] methods = Class1.getdeclaredmethods ()//Get all declarative methods of the class object method[] Allmethods = Class1.getmethods (); Gets all the methods of the class object, including the parent class's method class ParentClass = Class1.getsuperclass ();//Gets the parent class of the class object class<?>[] interfaceclasses = Class1.getinterfaces ()//Get all the interfaces of the class object constructor<?>[] Allconstructors = Class1.getdeclaredconstructors ()
;//Get all the declaration constructors for the class object constructor<?>[] Publicconstructors = class1.getconstructors ()//Get the class object public constructor try {constructor<?> constructor = Class1.getdeclaredconstructor (New Class[]{string.class});//Get the specified declaration constructor Constr Uctor publicconstructor = Class1.getconstructor (New class[]{});//Gets the public constructor for the specified declaration, catch (NosuchmethOdexception e) {e.printstacktrace ();} annotation[] annotations = class1.getannotations ()//Get all annotations of the class object Annotation Annotation = Class1.getannotation ( Deprecated.class)//Get the Class object to specify the annotation type Genericsuperclass = Class1.getgenericsuperclass ();//Get the type type of the direct superclass of the class object
[] interfacetypes = Class1.getgenericinterfaces ();//Gets the type collection for all interfaces of the class object
4.) Class object Dynamic generation
The first way class object calls the Newinstance () method to generate
object obj = Class1.newinstance ();
The second way object obtains the corresponding constructor object, and then generates Constructor<?> constructor by the Newinstance () method of the constructor object.
Class1.getdeclaredconstructor (New Class[]{string.class});//Get the specified declaration constructor
obj = constructor.newinstance (New Object []{"LCJ"});
5.) Dynamic Call function
try {
//Generate new object: With Newinstance () method
Object obj = Class1.newinstance ();
Determines whether the object is a subclass of person,
boolean isinstanceof = obj instanceof person;
First you need to obtain the method object
("Setage", New Class[]{int.class}) that corresponds to this approach;
Invokes the specified function and passes
the parameter method.invoke (obj);
method = Class1.getdeclaredmethod ("Getage");
Object result = Method.invoke (obj, new class[]{});
catch (Instantiationexception e) {
e.printstacktrace ();
} catch (Illegalaccessexception e) {
E.printstacktrace ();
} catch (Nosuchmethodexception e) {
e.printstacktrace ();
} catch (InvocationTargetException e) {
E.printstacktrace ();
}
6.) Get generic type by reflection mechanism
For example, the following structure
People class public class
people<t> {}
//person class inherits people class public class
person<t> extends People <String> implements personinterface<integer> {}
//personinterface interface public
interface personinterface<t> {}
Get generic type
person<string> person = new person<> ();
The first way is to
class<?> class1 = Person.getclass () by means of object GetClass method;
Type Genericsuperclass = Class1.getgenericsuperclass ()//Gets the type of the direct superclass of the class object
type[] Interfacetypes = Class1.getgenericinterfaces ();//Gets the type set
Getcomponenttype (Genericsuperclass) of all interfaces of the class object;
Getcomponenttype (Interfacetypes[0]);
Getcomponenttype Concrete Implementation
Private class<?> Getcomponenttype (type type) {
class<?> componenttype = null;
The IF (type instanceof parameterizedtype) {
//getactualtypearguments () returns an array of type objects that represent the actual type parameters of this type.
type[] actualtypearguments = (parameterizedtype) Type). Getactualtypearguments ();
if (actualtypearguments!= null && actualtypearguments.length > 0) {
ComponentType = (class<?>) ACTU Altypearguments[0];
}
else if (type instanceof genericarraytype) {
//indicates that an element type is a parameterized type or an array type of a type variable
componenttype = (class<?>) ( Genericarraytype) type). Getgenericcomponenttype ();
else {
ComponentType = (class<?>) type;
}
return componenttype;
}
6.) To obtain annotation information through reflection mechanism
Here the key is to get the annotation information of method as an example
try {
//First you need to get the method object that corresponds to this approach methods
= Class1.getdeclaredmethod ("Jumptogoodsdetail", New class[]{ String.class, String.class});
annotation[] annotations1 = method.getannotations ()//Get all the method annotation information
Annotation annotation1 = method.getannotation ( Routeruri.class)//Get the specified annotation information
typevariable[] typeVariables1 = Method.gettypeparameters ();
annotation[][] Parameterannotationsarray = method.getparameterannotations ()//Get all parameter annotation information
class<?>[] Parametertypes = Method.getparametertypes ()//Get All Parameters class type
type[] Genericparametertypes = Method.getgenericparametertypes ()//Gets the type of all parameters
class<?> returntype = Method.getreturntype (); Gets the return type of the method
int modifiers = method.getmodifiers ();//access permission to get method
} catch (Nosuchmethodexception e) {
E.printstacktrace ();
}
Application Scenarios for reflection mechanisms:
- Reverse code, such as Decompile
- Frames that are combined with annotations such as retrofit
- Simple reflection mechanism application framework such as Eventbus 2.x
- dynamically generating class frameworks such as Gson
Advantages and disadvantages of reflection mechanism:
Advantages: Runtime type of judgment, dynamic class loading, dynamic proxy using reflection.
Disadvantage: Performance is a problem, reflection is equivalent to a series of interpretation operations, to inform the JVM to do things, performance is much slower than direct Java code.
Summarize:
Java reflection mechanism in peacetime business development process is rarely used, but in some basic framework of the application is very broad, today a simple summary of learning, there are a lot of unknown knowledge and so on later to be supplemented.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.