反射是一种在运行时处理Java类的非常有用的方法,它可用于加载Java类,调用其方法或在运行时分析该类。
在此示例中,您将加载一个名为“ AppTest ”的类,并在运行时调用其每个方法。
1. AppTest.java
稍后将在运行时调用此Java类及其方法
package com.mkyong.reflection;
public class AppTest{
private int counter;
public void printIt(){
System.out.println("printIt() no param");
}
public void printItString(String temp){
System.out.println("printIt() with param String : " + temp);
}
public void printItInt(int temp){
System.out.println("printIt() with param int : " + temp);
}
public void setCounter(int counter){
this.counter = counter;
System.out.println("setCounter() set counter to : " + counter);
}
public void printCounter(){
System.out.println("printCounter() : " + this.counter);
}
}
2. ReflectApp.java
此类将加载“ AppTest ”类并在运行时调用其方法。 代码和注释是不言自明的。
package com.mkyong.reflection;
import java.lang.reflect.Method;
public class ReflectApp{
public static void main(String[] args) {
//no paramater
Class noparams[] = {};
//String parameter
Class[] paramString = new Class[1];
paramString[0] = String.class;
//int parameter
Class[] paramInt = new Class[1];
paramInt[0] = Integer.TYPE;
try{
//load the AppTest at runtime
Class cls = Class.forName("com.mkyong.reflection.AppTest");
Object obj = cls.newInstance();
//call the printIt method
Method method = cls.getDeclaredMethod("printIt", noparams);
method.invoke(obj, null);
//call the printItString method, pass a String param
method = cls.getDeclaredMethod("printItString", paramString);
method.invoke(obj, new String("mkyong"));
//call the printItInt method, pass a int param
method = cls.getDeclaredMethod("printItInt", paramInt);
method.invoke(obj, 123);
//call the setCounter method, pass a int param
method = cls.getDeclaredMethod("setCounter", paramInt);
method.invoke(obj, 999);
//call the printCounter method
method = cls.getDeclaredMethod("printCounter", noparams);
method.invoke(obj, null);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
3.输出
printIt() no param
printIt() with param String : mkyong
printIt() with param int : 123
printCounter() : 999
翻译自: https://mkyong.com/java/how-to-use-reflection-to-call-java-method-at-runtime/