Summary of Reflection Usage in JAVA Programming
- 2021-11-01 03:12:32
- OfStack
The basic knowledge of Java reflection is explained and summarized below:
First, define an MyBase class with both private and public fields. There are also public and private methods. An example of the MyBase class is as follows:
package com.hwdev.demo;
/**
* Sample base class
* @author wangming
*/
public class MyBase {
// Public field
public int version = 1;
// Private field
private String date = "2021-05-18" ;
// Commonwealth method
public void say2(String msg){
System.out.println("Hello " + msg);
}
// Private method
private String getData(){
return this.date;
}
}// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting
Here, another Hello class is defined, which inherits from MyBase class. Through inheritance, it is mainly used to verify the reflection usage of parent class and subclass under 1.
package com.hwdev.demo;
/**
*
* @author wangming
*/
public class Hello extends MyBase {
public String author = "JackWang" ;
public int version = 1;
private String company = "kzcloud" ;
public void say(String msg){
System.out.println("Hello " + msg);
}
public void setAuthor(String author){
this.author = author;
}
public String getAuthor(){
return this.author;
}
private int getVersion(){
return this.version;
}
}
With regard to Java reflection, the powerful function is that it can dynamically call methods from the system or modify the field value of one of the objects through string configuration, while Class. forName methods can obtain the corresponding Class objects by passing in the class full path string name, which is very convenient. In addition, the getField method and GetMethod method can get the specified fields and methods and call them dynamically.
package com.hwdev.demo;
import java.lang.reflect.*;
import java.util.Arrays;
/**
* Reflectance diaphragm 1 Kinds of usage Class.forName
* @author wangming
*/
public class ReflectDemo01 {
public static void Test() {
try
{
// Find by string full path class name Class
Class helloC = Class.forName("com.hwdev.demo.Hello");
// Gets all public field arrays, private ones cannot be obtained
Field [] fields = helloC.getFields();
// Print the contents of the field array // Join Java Develop and exchange samples: 7565848221 Blowing water and chatting
System.out.println(Arrays.toString(fields));
//[public java.lang.String com.hwdev.demo.Hello.author, public int com.hwdev.demo.Hello.version]
// Instantiation
Object obj = helloC.newInstance();
// Gets a specific field, more than traversing Field[] More efficient
Field f = helloC.getField("author");
if (f != null){
// Close safety inspection and improve efficiency
f.setAccessible(true);
// Get a field author Content
String author = (String)f.get(obj);
System.out.println("author=" + author);
//author=JackWang
}
// Gets all public method arrays, private methods cannot be obtained
Method [] methods = helloC.getMethods();
// Print method array content , Subclasses and other methods can also get
System.out.println(Arrays.toString(methods));
// All methods of this class
Method [] methods2 = helloC.getDeclaredMethods();
// Print method array content
System.out.println(Arrays.toString(methods2));
// Gets the specific method, the 2 Parameters String.class For say Parameter type of method
//say(java.lang.String)
Method m = helloC.getDeclaredMethod("say",String.class);
if (m != null){
// Close safety inspection and improve efficiency
m.setAccessible(true);
// Get a field author Content
Object returnValue = m.invoke(obj, new Object[]{"Java"});
//Hello Java
if (returnValue!=null){
System.out.println("returnValue =" + returnValue);
}
}// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting
}catch(ClassNotFoundException | SecurityException ex){
ex.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
Note here that the xxx. getMethods () method returns public methods of the class, parent class, and parent interface by default, while xxx. getDeclaredMethods () returns all methods of the class, including private methods. Similarly, other getXXX and getDeclaredXXX in reflective API are used similarly.
package com.hwdev;
import com.hwdev.demo.ReflectDemo01;
/**
*
* @author wangming
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Reflectance diaphragm 1 Kinds of usage Class.forName
ReflectDemo01.Test();
}
}
Execute the program and the output is as follows:
[public java.lang.String com.hwdev.demo.Hello.author, public int com.hwdev.demo.Hello.version, public int com.hwdev.demo.MyBase.version] author=JackWang [public void com.hwdev.demo.Hello.say(java.lang.String), public void com.hwdev.demo.Hello.setAuthor(java.lang.String), public java.lang.String com.hwdev.demo.Hello.getAuthor(), public void com.hwdev.demo.MyBase.say2(java.lang.String), public final void java.lang.Object.wait() throws java.lang.InterruptedException, public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()] [public void com.hwdev.demo.Hello.say(java.lang.String), public void com.hwdev.demo.Hello.setAuthor(java.lang.String), public java.lang.String com.hwdev.demo.Hello.getAuthor(), private int com.hwdev.demo.Hello.getVersion()] Hello Java
According to the output results,
Field [] fields = helloC.getFields();
You can get not only the public fields of the Hello class, but also the public fields of the parent class MyBase:
com.hwdev.demo.MyBase.version
And Method [] methods2 = helloC. getDeclaredMethods (); You can get all the methods of this class, that is, the Hello class, including public methods and private methods. Therefore, Java reflection can access private fields and methods of a class, exposing internal information, which is why Java reflection has security issues.
Because Java methods support overloading, there can be multiple methods with the same name, that is, different parameters. Therefore, when calling methods with reflection, it is necessary to specify the parameter types of methods, so that you can specify which method signature to call, such as ` Method m = helloC. getDeclaredMethod ("say", String. class); ` public void com. hwdev. demo. Hello. say (java. lang. String) ` is called.
In addition to using Class. forName for reflection, reflection objects can also be obtained in the following ways:
Hello hello = new Hello();
Class helloC = hello.getClass();
Field [] fields = helloC.getFields();
//
Class helloC = Hello.class;
Field [] fields = helloC.getFields();
Here's an example of how to modify a private field and call a private method using Java reflection under 1:
package com.hwdev.demo;
import java.lang.reflect.*;
/**
* Reflection accesses private fields and methods
* @author wangming
*/
public class ReflectDemo02 {
// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting
public static void Test() {
try
{
// Find through an existing class Class
Class helloC = Hello.class;
// Instantiation
Object obj = helloC.newInstance();
// Gets a specific private field
Field f = helloC.getDeclaredField("company");
if (f != null){
// Private must be turned on
f.setAccessible(true);
// Setting private field values
f.set(obj, "newKZ");
// Get a field author Content
String fv = (String)f.get(obj);
System.out.println("company=" + fv);
//company=newKZ
}
// Get private method
Method m = helloC.getDeclaredMethod("getVersion", null);
if (m != null){
// Private must be turned on
m.setAccessible(true);
Object returnValue = m.invoke(obj, null);
if (returnValue!=null){
//returnValue =1
System.out.println("returnValue =" + returnValue);
}
}
}catch(SecurityException ex){
ex.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
In addition, Java reflection can obtain annotation information, which is widely used for ORM framework.
package com.hwdev.demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation example
* @author wangming
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ORMAnnotation {
public String FieldName();
public String FieldType();
}
Where @ Retention (RetentionPolicy. RUNTIME) indicates that annotations can be accessed through reflection at run time. @ Target (ElementType. FIELD) means that this annotation can only be used on fields. Similarly, FIELD can be changed to Type or Method, etc.
package com.hwdev.demo;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
/**
* Reflection or field annotation
* @author wangming
*/// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting
public class ReflectDemo03 {
public static void Test() {
try
{
Class helloC = Class.forName("com.hwdev.demo.HelloAnnotation");
Field[] fields = helloC.getDeclaredFields();
for(Field f : fields){
// Close safety inspection and improve efficiency
f.setAccessible(true);
Annotation ann = f.getAnnotation(ORMAnnotation.class);
if(ann instanceof ORMAnnotation){
ORMAnnotation ormAnn = (ORMAnnotation) ann;
System.out.println("FieldName=" + ormAnn.FieldName());
System.out.println("FieldType=" + ormAnn.FieldType());
}
}
}catch(ClassNotFoundException | SecurityException ex){
ex.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
Execute this example, and the output is as follows:
FieldName=f_author FieldType=varchar(50) FieldName=f_ver FieldType=int
Thirdly, it introduces how to use reflection to obtain the number and type of method parameters under 1, including generic information acquisition:
package com.hwdev.demo;
import java.util.ArrayList;
import java.util.List;
/**
* Generic sample
* @author wangming
*/
public class GenericCls {
protected List<String> myList = new ArrayList();
public GenericCls(int size){
for(int i = 0;i<size;i++){
myList.add("item"+i);
}
}
public List<String> getList(){
return this.myList;
}
public String getList(int idx){
return this.myList.get(idx);
}
}
package com.hwdev.demo;
import java.lang.reflect.*;
/**
* Reflection acquisition method parameters
* @author wangming
*/
public class ReflectDemo05 {
public static void Test() {
try
{
// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting
Class helloC = Class.forName("com.hwdev.demo.GenericCls");
// Constructor call
Object obj = helloC.getConstructor(int.class).newInstance(3);
Method method = helloC.getMethod("getList", int.class);
Class<?> returnType = method.getReturnType();
System.out.println("ReturnType = " + returnType.getName());
Parameter[] params = method.getParameters();
for(Parameter p : params){
System.out.println("ParameterizedType = " + p.getParameterizedType());
System.out.println("getModifiers = " + p.getModifiers());
System.out.println("getName = " + p.getName());
System.out.println("getType = " + p.getType());
}
// Invoke method
Object ret = method.invoke(obj, new Object[]{2});
System.out.println("ret = " + ret.toString());
Method method2 = helloC.getMethod("getList", null);
Type greturnType = method2.getGenericReturnType();
System.out.println("getGenericReturnType = " + returnType.getName());
if(greturnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) greturnType;
System.out.println("type = " + type.getTypeName());
Type[] typeArguments = type.getActualTypeArguments();
for(Type typeArgument : typeArguments){
Class typeArgClass = (Class) typeArgument;
System.out.println("typeArgClass = " + typeArgClass);
}
}
}catch(ClassNotFoundException | SecurityException ex){
ex.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
Execute this example, and the output is as follows:
R`eturnType = java.lang.String ParameterizedType = int getModifiers = 0 getName = arg0 getType = int ret = item2 getGenericReturnType = java.lang.String type = java.util.List < java.lang.String > typeArgClass = class java.lang.String
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!