通过反射可以获取类的实例对象,进而获取它的方法。
被反射的类:
package test;
public class User {
private String sname;
private String ssss;
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSsss() {
return ssss;
}
public void setSsss(String ssss) {
this.ssss = ssss;
}
}
实现类:
public static void main(String[] args) {
String className ="test.User";
try {
Class c = Class.forName(className);
Object obj = c.newInstance();
String name ="linzj";
Method[] methods = c.getMethods();
for(Method method: methods){
if("setSname".equals(method.getName())){
method.invoke(obj, new Object[]{name}); //方法调用注意 参数
}
if("getSname".equals(method.getName())){
String str = (String) method.invoke(obj, new Object[]{});
System.out.println("name="+str);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
注意:
getDeclaredMethod*()获取的是类自身声明的所有方法,包含public、protected和private方法。
getMethod*()获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。
内部类的反射:
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestRe {
/**
* Reflect 反射实例
* @param args
*/
public static void main(String[] args) {
String className ="test.TestRe$Inner"; //内部类
try {
Class clazz = Class.forName(className);
Object obj = clazz.getConstructors()[0].newInstance(new TestRe()); // <span style="font-family: Arial, Helvetica, sans-serif;">new TestRe() 是外部类实例对象</span>
Method[] methods = clazz.getMethods();
for(Method method: methods){
if("getStr".equals(method.getName())){
String str = (String) method.invoke(obj, new Object[]{});
System.out.println("getstr="+str);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
class Inner {
public Inner(){}
public String getStr(){
return "inner class coming";
}
}