一,加载类字节码文件到内存的方法
- 类名.Class
- 对象.getClass
- Class.forName(); //传包名和类名
二,获取构造方法
- getConstructor() //获取public类型的指定构造器
public class Test {
@org.junit.Test
public void createObj() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
Class<Student> clazz = Student.class;
Constructor<Student> con = clazz.getDeclaredConstructor();
con.setAccessible(true);
//创建空参对象
Student student = con.newInstance();
//获取指定变量
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
//为变量赋值
name.set(student,"张三");
Field age = clazz.getDeclaredField("age");
age.setAccessible(true);
age.set(student,14);
Field score = clazz.getDeclaredField("score");
score.setAccessible(true);
score.set(student,88.8);
System.out.println(student);
}
}
- getDeclaredConstructor //获取只要存在就能拿到的构造器
Class<Cat> clazz = Cat.class;
//参数为字节码文件
Constructor<Cat> con = clazz.getDeclaredConstructor(String.class,int.class);
//取消访问权限
con.setAccessible(true);
//带参创建对象
Cat cat = con.newInstance("失败",3);
- getConstructors() //获取全部public类型的构造器
- getDeclaredConstructors() //获取全部只要存在就能拿到的构造器
三,获取成员变量
- getFields();
- getDeclaredFields();
- getDeclaredField();
Class<Cat> clazz = Cat.class;
System.out.println("-------获取全部public变量----------");
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("--------获取全部变量---------");
Field[] names = clazz.getDeclaredFields();
for (Field field : names) {
System.out.println(field);
}
System.out.println("--------获取指定名称变量---------");
Field name = clazz.getDeclaredField("name");
System.out.println(name);
System.out.println("---------变量赋值--------");
Cat cat = new Cat();
name.setAccessible(true);
name.set(cat,"失败");
System.out.println(cat);
System.out.println("--------变量取值---------");
String o = (String) name.get(cat);
System.out.println(o);
}
四,获取方法
- getDeclaredMethods();
- getDeclaredMethod(); //参数为(方法名,方法参数类型)
@Test
public void testMethods() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
System.out.println("-----------获取所有方法-------------");
Class<Cat> clazz = Cat.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName() + "-->" + method.getParameterCount() + "-->" + method.getReturnType());
}
System.out.println("-------------使用带参方法-------------");
//参数为(方法名,方法参数类型)
Method fun = clazz.getDeclaredMethod("fun", String.class);
Cat cat = new Cat();
//执行,参数为(obj,方法参数)
fun.invoke(cat,"哈哈");
System.out.println("------------使用无参方法--------------");
Method method = clazz.getDeclaredMethod("fun");
method.invoke(cat);
}