Reflection can solve the problem that it is impossible to predict at compile time which objectand class it belongs to, and the information of the object and class can only be known based on the information when the program is running.
When two people collaborate on development, you only need to know the other party's class name to carry out preliminary development.
Class.forName(String clazzName) static method
Call the class attribute of the class, Person. class returns the Person class object (recommended)
Call the getClass() method of an object
Specific use You still have to choose based on actual conditions. The first method is relatively free. You only need to know a class name. It will not verify whether the class exists. The second and third methods will verify whether the class exists.
##Connstructor: Returns the public constructor with specified formal parameters of the corresponding class of this Class object
Constructor>[] getConstructors() :Return all public constructors of the class corresponding to this Class object
:Return This class object corresponds to the constructor of the class with specified parameters, regardless of the access permission of the constructor
Get the class member variables
Get class annotation
##<A extends Annotation>A getDeclaredAnnotation(Class<A>annotationClass)
:This It is new in Java 8. This method obtains the Annotation of the specified type that directly modifies the corresponding class of the class object. If it does not exist, it returns null
##Annotation[] getAnnotations (): Returns all the Annotations that exist on the corresponding class that modifies the class object
Annotation[] getDeclaredAnnotations(): Returns the class corresponding to the modified Class object All Annotations that exist on
: The function of this method is the same as the getAnnotation introduced earlier The () method is basically similar, but since Java8 has added the repeated annotation function, you need to use this method to obtain multiple Annotations of the specified type that modify the class
##Class<?>[] getDeclaredClasses()
:Return all internal classes contained in the corresponding class of the class formation
Class<?> getDeclaringClass()
: Returns the external class where the corresponding class of the Class object is located
Class<?>[] getInterfaces()
: Returns all interfaces implemented by the corresponding class of the Class object
##Class super T> getSuperclass(): Return the The Class object of the super class corresponding to the Class object
int getModifiers(): Returns all modifiers of this class or interface. The modifiers are composed of public, protected, private, final, static, abstract and other corresponding constants. The returned
integerYou should use the method of the Modifier tool class to decode to get the real modifier
Package getPackage(): Get the package of this class
String getName(): Returns the short name of the class represented by this CLass object in the form of
string
boolean isAnnotation(): Returns whether this class object represents an annotation type
boolean isAnnotationPresent(Class extends Annotation>annotationClass): Determine whether this Class object is decorated with class Annotation
boolean isAnonymousClass(): Returns whether this class object is an
anonymous class
: Returns this class object Whether it represents an array
class
: Returns whether this class object represents an enumeration
: Returns whether this class object represents an interface
obj ): Determine whether obj is an instance of this class object. This method can completely replace the instanceof<a href="http://www.php.cn/wiki/60.html" target="_blank"> operator</a>
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() false true
New method parameter reflection in Java8
public class Test { public void getInfo(String str,List<String>list){ System.out.println("成功"); } }
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()); } } }
2 2 arg0 class java.lang.String class java.lang.String arg1 interface java.util.List java.util.List<java.lang.String>
Reflection generated object
Use the newInstance() method of the Class object to create an instance of the Class object. This method requires a default constructor (more commonly used) 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.class; Constructor<Test>construct=cls.getConstructor(String.class); Test test=construct.newInstance("初始化"); Method med=cls.getMethod("getInfo", String.class); med.invoke(test, "调用方法成功"); } }
初始化 调用方法成功
Next, the official will take a closer look at the chestnut below
public class Test { public Test(String str) { System.out.println(str); } //私有方法 private void getInfo(String str){ System.out.println(str); } }
public class ClassInfo { public static void main(String[] args) throws Exception { Class<Test> cls=Test.class; Constructor<Test>construct=cls.getConstructor(String.class); Test test=construct.newInstance("初始化"); //为啥使用这个方法呢? Method med=cls.getDeclaredMethod("getInfo", String.class); //为啥使用这个方法呢? med.setAccessible(true); med.invoke(test, "调用方法成功"); } }
Result
初始化 调用方法成功
setAccessible(boolean flag): Set the value to true, indicating that the Java language access permission check should be canceled when using this Method Accessing member variable values
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; } }Copy after loginResultpublic class ClassInfo { public static void main(String[] args) throws Exception { Class<Test> cls=Test.class; Constructor<Test>construct=cls.getConstructor(String.class); Test test=construct.newInstance("初始化"); Method med=cls.getDeclaredMethod("getInfo", String.class); med.setAccessible(true); med.invoke(test, "调用方法成功"); Field fld=cls.getDeclaredField("num"); fld.setAccessible(true); fld.setInt(test, 12); System.out.println(fld.getInt(test)); } }Copy after login
初始化 调用方法成功 12
Operation array
There is an Array under the java.lang.reflect package Class, which can dynamically create arraysstatic Object newInstance(Class>componentType,int...length)
: Create a new array with the specified element type and specified dimensionsstatic xxx getXxx(Object array,int index)
:返回array数组中第index个元素。其中xxx是各种基本数据类型,如果数组元素是引用类型,则该方法变为get()
static void setXxx(Object array,int index,xxx val)
:将array数组中低index 个元素的值设为val,其中xxx是各种基本数据类型,如果数组元素是引用类型,则该方法变为set()
public class ArrayInfo { public static void main(String[] args) { Object arrays=Array.newInstance(String.class, 3); Array.set(arrays, 0, "第一个"); Array.set(arrays, 1, "第二个"); Array.set(arrays, 2, "第三个"); System.out.println(Array.get(arrays, 2)); } }
The above is the detailed content of Detailed introduction to Java reflection to obtain class and object information. For more information, please follow other related articles on the PHP Chinese website!