获取字节码文件的三种方式:
Class.froname();
类名.getclass();
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class day1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// 成员私有属性赋值
Class sud = Class.forName("sud");
sud o = (sud) sud.newInstance();
Field age = sud.getDeclaredField("age");
age.setAccessible(true);
age.set(o,14);
System.out.println(o.getAge());
// 构造方法
Constructor declaredConstructor = sud.getDeclaredConstructor(int.class,String.class);
Object o1 = declaredConstructor.newInstance(14,"ss");
declaredConstructor.setAccessible(true);
System.out.println(o1);
// 方法
Method declaredMethod = sud.getDeclaredMethod("setAge", int.class);
Object invoke = declaredMethod.invoke(o,4);
System.out.println(invoke);
}
}
class sud{
private int age;
private String name;
public sud() {
}
public sud(int age, String name) {
this.age = age;
this.name = name;
}
public void setAge(int age) {
this.age = age;
System.out.println(age);
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "sud{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}