前提:
由对象获取一个.class对象:Class clazz = "hello world".getClass(); 由对象的全包名获取一个.class对象:
Class clazz=Class.forName("java.lang.String");
学习的时候发现,int等基本数据类型不是对象,所以无法获得其class对象,使用过程中只能通过int.class获取
正文:
实体类package test;
public class Student {
private static Student student = new Student();
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void method1(int param1,String param2) {
System.out.println(param1+param2);
}
}
测试类:package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
Student stu = new Student();
stu.setAge(1);
stu.setName("lin");
//1.无参
Method method = stu.getClass().getMethod("getName");
String name = (String) method.invoke(stu);
//2.一参
Method method2 = stu.getClass().getMethod("setName",Class.forName("java.lang.String"));
method2.invoke(stu, "meng");
//3.多参
Method method3 = stu.getClass().getMethod("method1",int.class,Class.forName("java.lang.String"));//后两个参数获得的都是class对象
method3.invoke(stu,15, "zhang");
}
}
另附自写get和set函数://参数列表:
//1.目标所属对象 2.所用set函数名(全称不加()) 3.set值public void set(Info info,String fun,Object value) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
Method method = info.getClass().getMethod(fun,Class.forName(value.getClass().getCanonicalName()));
method.invoke(info, value);
}
public Object get(Info info,String fun) throws Exception {
Method method = info.getClass().getMethod(fun);
return method.invoke(info);
}使用过程中可自行将函数封装进模板类代替Info类
由于Object无法接收int等基本数据类型,故在实体类中时可将类型声明为Integerpublic Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}