放射,说白了就是通过名字加载相应的类,以及类的方法和属性,是为了解决开发中不知道别人会写什么类而采取的一种顺利开发的东东。
package com.io;
//学生业务类 不知道别人写的 这个是别人写的
//放射机制必须要有包名
class stu {
private String stuname;
private int age;
public void addStu(String stuname){
this.stuname=stuname;
System.out.println(stuname);
}
public void showstu(){
System.out.println(stuname);
}
}
//通过名字,获取对象实例,方法,并且调用
package com.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class demo1 {
//他告诉我类名是stu , com.io包里面
public static void main(String[] args) {
String classname ="com.reflectdemo.stu";
try {
Class call= Class.forName(classname);
System.out.println(call.getName());
Object obj = call.newInstance();
Method methods[] = call.getMethods();
Method method = call.getMethod("addStu",String.class);
method.invoke(obj, "zhansan");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}