Reflection resolves an issue in which objects and classes are not predictable at compile time, and information about the object and class is not known until the program runs.
When two people collaborate on development, you can do the initial development by knowing the other person's class name.
Get Class object
- Class.forName (String clazzname) static method
- invokes the class property of the Person.class, which returns the person's class object (recommended)
- Call the GetClass () method of an object
Specific use or to choose according to the actual, the first way is relatively free, as long as you know a class name can be, it does not do the existence of the check, the second, the third will do the check
Get information about a class get class Builder
Connstructor<T> getConstructor(Class<?>...parameterTypes)
: Returns the public constructor with the specified parameters for the class of this class object
Constructor<?>[] getConstructors()
: Returns all public constructors for the class of this class object
Constructor<T>[] getDeclaredConstructor(Class<?>...parameterTypes)
: Returns the constructor with the specified parameters for the class of the classes object, independent of the constructor's access rights
Constructor<?>[] getDeclaredConstructors()
: Returns all constructors for classes of this class object, regardless of the constructor's access rights
Get class member methods
Method getMethod(String name,Class<?>...parameterTypes)
: Returns the public method with the specified parameters for the class of this class object
Method[] getMethods()
: Returns all public methods of the class represented by this class object
Method getDeclaredMethod(string name,Class<?>...parameterTypes)
: Returns the method with the specified parameter for the class of this class object, regardless of the method access permission
Method[] getDeclaredMethods()
: Returns all the methods of the class object corresponding to the access rights of the method
Get class member variable
Field getField(String name)
: Returns the public member variable for the specified name of the class for this class object
Field[] getFields()
: Returns all public member variables for the class of this class object
Field getDeclaredField(String name)
: Returns the member variable of the specified name of the class object corresponding to the member variable access permission
Field[] getDeclaredFields()
: Returns all member variables of the class object corresponding to the access rights of the member variable
Get class annotations
<A extends Annotation>A getAnnotation(Class<A>annotationClass)
: Attempts to obtain the annotation of the specified type of the village on the class object, and returns null if the type annotation does not exist
<A extends Annotation>A getDeclaredAnnotation(Class<A>annotationClass)
: This is new in Java 8, which gets the annotation of the specified type that directly modifies the class of that class object, and returns null if it does not exist.
Annotation[] getAnnotations()
: Returns all annotation that exist on the class object corresponding to
Annotation[] getDeclaredAnnotations()
: Returns all annotation that exist on the class object corresponding to
<A extends Annotation>A[] getAnnotationByType(Class<A>annotationClass)
: The function of this method is basically similar to the Getannotation () method described earlier, but because Java8 adds a repeating annotation feature, you need to use this method to get more than one annotation that modifies the specified type of the class.
<A extends Annotation>A[] getDeclaredAnnotationByType(Class<A>annotationClass)
: This method is similar to the Getdeclaredannotations () method described earlier, and is also because of the repetitive annotation function of Java8, which requires the method to obtain multiple annotation that directly decorate the specified type of the class.
Gets the class inner class
Class<?>[] getDeclaredClasses()
: Returns all the inner classes contained in the class formation corresponding classes
Gets the outer class where the class object resides
Class<?> getDeclaringClass()
: Returns the outer class where the class object corresponds
Gets the interface implemented by the class for the class object
Class<?>[] getInterfaces()
: Returns all interfaces implemented by the class object's corresponding classes
Gets the parent class for which the class object class inherits
Class<? super T> getSuperclass()
: The class object that returns the superclass of the class object
Gets the basic information about the class's modifier, package, class name, and so on for the class object
int getModifiers()
: Returns all the modifiers for this class or interface, which consist of the constants of public, protected, private, final, static, abstract, and so on, and the returned integers should be decoded using the method of the Modifier tool class. To get the real modifier.
Package getPackage()
: Gets the package for this class
String getName()
: Returns the short name of the class represented by this class object as a string.
Determines whether the class is an interface, enumeration, annotation type
boolean isAnnotation()
: Returns whether this class object represents an annotation type
boolean isAnnotationPresent(Class<? extends Annotation>annotationClass)
: Determines whether this class object uses the annotation adornment
boolean isAnonymousClass()
: Returns whether this class object is an anonymous class
boolean isArray()
: Returns whether this class object represents an array class
boolean isEnum()
: Returns whether this class object represents an enumeration
boolean isInterface()
: Returns whether this class object represents an interface
boolean isInstance(Object obj)
: Determines if obj is an instance of this class object, which can completely replace the instanceof operator
Public interface colorable {public void value ();}
public class ClassInfo {public static void Main (string[] args) throws Nosuchmethodexception, SecurityException {
class<colorable> Cls=colorable.class; System.out.println (Cls.getmethod ("value")); System.out.println (Cls.isannotation ()); System.out.println (Cls.isinterface ());} }
结果
public abstract void Com.em.Colorable.value () falsetrue
New method parameter Reflection in Java8
int getParameterCount()
: Gets the number of parameters for the constructor or method
Parameter[] getParameters()
: Gets all the parameters of the constructor or method
getModifiers()
: Gets the modifier that modifies the parameter
String getName()
: Get formal parameter names
Type getParameterizedType()
: Gets the type of the parameter with the generic type
Class<?>getType()
: Getting formal parameter types
boolean isNamePresent()
: This method returns whether the class file of the classes contains the parameter name information for the method
boolean isVarArgs()
: This method is used to determine whether the parameter is a variable number of formal parameters
public class Test {public void GetInfo (String str,list<string>list) { System.out.println ("Success");} }
public class ClassInfo {public static void Main (string[] args) throws Nosuchmethodexception, SecurityException {
class<test> Cls=test.class; Method Med=cls.getmethod ("GetInfo", string.class,list.class); System.out.println (Med.getparametercount ()); Parameter[] Params=med.getparameters (); System.out.println (params.length); for (Parameter par:params) { System.out.println (Par.getname ()); System.out.println (Par.gettype ()); System.out.println (Par.getparameterizedtype ());}}}
结果
22arg0class Java.lang.Stringclass Java.lang.Stringarg1interface java.util.listjava.util.list<java.lang.string >
Reflection-generated objects
- Use the Newinstance () method of the class object to create an instance of the class object that requires a default constructor (more commonly used)
- Use the class object first to get the specified constructor object, and in the call to the constructor object's Newinstance () method to create an instance of the class object corresponding to
Reflection Call Method
Object invoke(Object obj,Object...args)
: Obj In this method is the keynote that executes the method, and the following args is the argument that is passed in when the method is executed
public class Test {public Test (String str) { System.out.println (str); } public void GetInfo (String str) { System.out.println (str);} }
public class ClassInfo {public static void Main (string[] args) throws Exception { class<test> cls=test.cl the; Constructor<test>construct=cls.getconstructor (string.class); Test test=construct.newinstance ("Initialize"); Method Med=cls.getmethod ("GetInfo", string.class); Med.invoke (Test, "call method succeeded");} }
结果
Initialize Call method succeeded
Next crossing look closely at the chestnuts below
public class Test {public Test (String str) { System.out.println (str); } Proprietary method Private void GetInfo (String str) { System.out.println (str);} }
public class ClassInfo {public static void Main (string[] args) throws Exception { class<test> Cls=test.cla SS; Constructor<test>construct=cls.getconstructor (string.class); Test test=construct.newinstance ("Initialize"); Why use this method? Method Med=cls.getdeclaredmethod ("GetInfo", string.class); Why use this method? med.setaccessible (true); Med.invoke (Test, "call method succeeded");} }
结果
Initialize Call method succeeded
Setaccessible (Boolean flag): Sets the value to true to indicate that the method is in use and that the Java language's access check should be canceled
accessing member variable values
getXxx(Object obj)
: Gets the value of this member variable for the Obj object. Here XXX corresponds to 8 basic types, if the type of the member variable is a reference type, then remove the xxx part
setXxx(Object obj,Xxx val)
: Sets the member variable of the Obj object to a Val value. The xxx here corresponds to the basic type in 8, and if the type of the member variable is a reference type, then the XXX after the set is canceled
The above two methods can be method for all member variables, including private member variables
public class Test { private int num; Public Test (String str) { System.out.println (str); } private void GetInfo (String str) { System.out.println (str); } public int Getnum () { return num; } public void setnum (int num) { this.num = num; }}
public class ClassInfo {public static void Main (string[] args) throws Exception { class<test> Cls=test.cla SS; Constructor<test>construct=cls.getconstructor (string.class); Test test=construct.newinstance ("Initialize"); Method Med=cls.getdeclaredmethod ("GetInfo", string.class); Med.setaccessible (true); Med.invoke (Test, "call method succeeded"); Field fld=cls.getdeclaredfield ("num"); Fld.setaccessible (true); Fld.setint (test,); System.out.println (Fld.getint (test));} }
结果
Initialize Call method succeeded 12
manipulating arrays
There is an array class under the Java.lang.reflect package that can dynamically create an array
static Object newInstance(Class<?>componentType,int...length)
: Creates a new array with the specified element type, specified dimension
static xxx getXxx(Object array,int index)
: Returns the index element of the array. where xxx is a variety of basic data types, if the array element is a reference type, then the method becomes get ()
static void setXxx(Object array,int index,xxx val)
: Sets the value of a low index element in the array array to Val, where xxx is a variety of base data types, and if the array element is a reference type, the method becomes set ()
public class ArrayInfo {public static void Main (string[] args) { Object arrays=array.newinstance (String.class, 3); Array.set (arrays, 0, "the first One"); Array.set (arrays, 1, "the second One"); Array.set (Arrays, 2, "third"); System.out.println (Array.get (arrays, 2));} }
Java reflection Get class and object information fully resolved