This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
package reflecttest;
public class Person {
public int age;
private String name;
public Person(a) {
// TODO automatically generated constructor stubs
}
public Person(String name) {
super(a);this.name = name;
}
private Person(String name,int age) {
super(a);this.name = name;
this.age = age;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(String name,int age) {
System.out.println("Deja, turn.");
}
private void fly(a) {
System.out.println("Deja, fly.");
}
private String Work(String name,int age) {
returnname; }}Copy the code
Three ways to get an instance of Class
An instance of Class is a runtime Class
-
Class via the Class literal constant class.class
Class clazz = Person.class; Copy the code
-
Return an instance of Class type through the getClass() method of the Object Class
Person person = new Person(); Class clazz = person.getClass(); Copy the code
-
Obtain the Class object corresponding to the Class name using the static method class.forname (” full Class name “)
Class clazz = Class.forName("reflecttest.Person"); Copy the code
Create objects through reflection
There are two main ways to create Class objects by reflection, through the newInstance() method of a Class object and through the newInstance() method of a Constructor object.
-
The first is through newInstance() on Class objects.
// Get an instance of the Class object Class clazz = Person.class; // Create Person object Person person = (Person)clazz.newInstance(); Copy the code
-
Second: newInstance() via the Constructor object
// Get an instance of the Class object Class clazz = Person.class; // Create Person object Constructor constructor = clazz.getConstructor(); Person person = (Person)constructor.newInstance(); Copy the code
Class objects created from a Constructor object can select a specific Constructor, whereas only the default no-argument Constructor can be used from a Class object.
Example :(calling the parameter constructor to initialize a class object)
// Get an instance of the Class object
Class clazz = Person.class;
// Create Person object
Constructor constructor = clazz.getConstructor();
Person person = (Person) constructor.newInstance("Tiga".16);
Copy the code
Invoke object properties through reflection
Retrieve attributes
Two ways to get all the attributes
-
getFields()
// Use getFields() to get the person.class and all public-decorated attributes in the parent class Field[] fields = clazz.getFields(); Copy the code
-
getDeclaredFields()
GetDeclaredFields () to get all the attributes in person.class Field[] fields = clazz.getDeclaredFields(); Copy the code
Note:
GetFields () retrieves all public attributes of this class and its parent. GetDeclaredFields () retrieves all attributes of this class. Include public, private, protected, and default-modified attributes, excluding those in the parent class
Two ways to get a specified property
-
getField(String name)
// Get the age property in person.class with getField() Field field = clazz.getField("age"); Copy the code
-
getDeclaredField(String name)
GetDeclaredField () to get the name attribute in person.class Field field = clazz.getDeclaredField("name"); Copy the code
Note:
GetField (String name) getDeclaredField(String name) getDeclaredField(String name) getDeclaredField(String name) Include public, private, protected, and default-modified attributes, excluding those in the parent class
Operations on properties
Setting property values
GetDeclaredField () to get the name attribute in person.class
Field field = clazz.getDeclaredField("name");
// If the property is private, access permissions need to be set to assign the value
field.setAccessible(true);
// Set (Object obj, Object value) to "dija"
field.set(person, "Tiga");
Copy the code
Note: If the property is private, you need to set setAccessible(true) to assign the value
Get property values
// Get the Field property of the Person Object through get(Object obj)
String name = (String) field.get(person);
Copy the code
Gets the type of the property
GetType () to get the type of the attribute
Class type = field.getType();
// Get the type name of the attribute
String typename = field.getType().getName();
Copy the code
Get attribute name
// Call getName() to get the property name
String fieldname = field.getName();
Copy the code
Get the modifier type
// Call getModifiers() to get modifier types,
int modifier = field.getModifiers();
ToString (int mod) change to public, private, protected, default
String modifiername = Modifier.toString(modifier);
Copy the code
Note :0-default, 1-public, 2-private, 4-protected
The sample
// Get an instance of the Class object
Class clazz = Person.class;
// Create Person object
Person person = (Person) clazz.newInstance();
GetDeclaredField () to get the name attribute in person.class
Field field = clazz.getDeclaredField("age");
field.setAccessible(true);
// Set the age property of the person object to "12" through set()
field.set(person, 12);
// Get the modifier
int modifier = field.getModifiers();
String modifiername = Modifier.toString(modifier);
// Get the attribute type name
String typename = field.getType().getName();
// Get the attribute name
String fieldname = field.getName();
// Get the attribute value
int fieldvalue = field.getInt(person);
System.out.println(modifiername+""+typename+""+fieldname+"="+fieldvalue+";");
Copy the code
Public int age = 12;
Call object methods through reflection
Access method
Two ways to get all the methods
-
getMethods()
// Use getMethods() to get all the public modifier methods in the Person class and its parent Method[] methods =clazz.getMethods(); Copy the code
-
getDeclaredMethods()
GetDeclaredMethods () to get all the methods in the Person class Method[] methods = clazz.getDeclaredMethods(); Copy the code
Note:
GetMethods () retrieves all public methods of this class and its parent. GetDeclaredMethods () retrieves all methods of this class. Methods that include public, private, protected, and default modifications, excluding methods in parent classes
Two ways to take the specified method
The method name and parameter list are used to determine the method to get
-
getMethod(String name, class<? >... parameterTypes)
// Get the show method from the Person class with the method name, the list of parameters for show() Method method =clazz.getMethod("show",String.class,int.class); Copy the code
-
GetDeclaredMethod (String name, class <? >... parameterTypes)
// Get the fly method from the Person class with the method name and the fly() invisible parameter list Method method = clazz.getDeclaredMethod("fly"); Copy the code
Note:
GetMethod () gets the public modifier of this class and its parent. GetDeclaredMethod () gets the public modifier of this class. Include public, private, protected, and default-modified attributes, excluding those in the parent class
Operations on methods
A method is called
// Get the fly method from the Person class with the method name and the fly() invisible parameter list
Method method = clazz.getDeclaredMethod("fly");
// If the method is private, you need to set the access permission
method.setAccessible(true);
// Call the fly method in person
method.invoke(person);
// If the method is static, the following method can be used: the current class calls the method
//method.invoke(Person.class);
Copy the code
Note: The return value of the invoke() method is the same as that of the called method
Gets the parameter list for the method
// Get the parameter list
Class[] paramTypes =method.getParameterTypes();
Copy the code
Get method name
// Get the method name
String methodname = method.getName();
Copy the code
Gets the modifier type of the method
// Get the method modifier
int modifier = method.getModifiers();
String modifiername = Modifier.toString(modifier);
Copy the code
Gets the return value type of the method
// Get the return value typeClass<? > returntype =method.getReturnType();// Get the name of the return value type
String returntypename = returntype.getName();
Copy the code
The sample
public static void main(String[] args) throws Exception, IllegalAccessException {
// Get an instance of the Class object
Class clazz = Person.class;
// Create Person object
Person person = (Person) clazz.newInstance();
// Get the method in the Person class
Method method = clazz.getDeclaredMethod("Work",String.class,int.class);
// Set permissions
method.setAccessible(true);
// Get the method name
String methodname = method.getName();
// Get the method modifier
int modifier = method.getModifiers();
String modifiername = Modifier.toString(modifier);
// Get the return value typeClass<? > returntype =method.getReturnType();// Get the name of the return value type
String returntypename = returntype.getName();
// Get the parameter list
Class[] paramTypes =method.getParameterTypes();
System.out.print(modifiername+""+returntypename+""+methodname+"(");
// Prints method parameters
printParamTypes(paramTypes);
}
/** * Print method arguments *@param paramTypes
*/
private static void printParamTypes(Class[] paramTypes) {
for (int j = 0; j < paramTypes.length; ++j) {
if (j > 0) {
System.out.print(",");
}
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
Copy the code
Private java.lang.String Work(java.lang.String,int);
Call the object constructor through reflection
Get constructor
Two ways to get all constructors
-
getConstructors()
// Get all public modifier constructors, excluding the parent class Constructor[] constructors = clazz.getConstructors(); Copy the code
-
getDeclaredConstructors()
// Get all constructors, including public, private, protected, default, excluding the parent class Constructor[] constructors = getDeclaredConstructors(); Copy the code
Note:
GetConstructors () can get in this class all public the structure of the modified method, not including the superclass getgetDeclaredConstructors () can get all this class constructor. Methods that include public, private, protected, and default modifications, excluding parent classes
Gets two ways to specify a constructor
The choice of constructor depends on the type of parameter list
-
clazz.getConstructor()
// Get a parameterless constructor Constructor constructor = clazz.getConstructor(); Copy the code
-
getDeclaredConstructor()
// Get a constructor that takes (String,int) Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class); Copy the code
Note:
GetConstructor () gets only the public constructor of this class, excluding the parent getDeclaredConstructor(). Methods that include public, private, protected, and default modifications, excluding parent classes
Operations on constructors
Create an object
The choice of constructor depends on the type of parameter list
// Get the constructor for the empty parameter
//Constructor constructor = clazz.getDeclaredConstructor();
Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);
// If the constructor is private, set permissions
constructor.setAccessible(true);
// Create person object
Person person = (Person)constructor.newInstance("Tiga".20);
Copy the code
Gets the constructor’s argument list
// Get the constructor parameter list
Class[] paramTypes = constructor.getParameterTypes();
Copy the code
Gets the constructor name
// Get the constructor name
String constructorname = constructor.getName();
Copy the code
Gets the modifier type of the constructor
// Get the constructor modifier
int modifier = constructor.getModifiers();
String modifiername = Modifier.toString(modifier);
Copy the code
The sample
public static void main(String[] args) throws Exception, IllegalAccessException {
// Get an instance of the Class object
Class clazz = Person.class;
// Get the constructor with parameters
Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);
// If the constructor is private, set permissions
constructor.setAccessible(true);
// Create person object
Person person = (Person)constructor.newInstance("Tiga".20);
// Get the constructor name
String constructorname = constructor.getName();
// Get the constructor modifier
int modifier = constructor.getModifiers();
String modifiername = Modifier.toString(modifier);
// Get the constructor parameter list
Class[] paramTypes = constructor.getParameterTypes();
System.out.print(modifiername+""+constructorname+"(");
// Prints method parameters
printParamTypes(paramTypes);
}
/** * Print method arguments *@param paramTypes
*/
private static void printParamTypes(Class[] paramTypes) {
for (int j = 0; j < paramTypes.length; ++j) {
if (j > 0) {
System.out.print(",");
}
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
Copy the code
Private test1.person (java.lang.string,int);