获取字节码 创建对象

package code;

import java.lang.reflect.Constructor;

public class CodeDemo {
	public static void main(String[] args) throws Exception {
		//1.通过字节码创建对象
		Class clazz = Class.forName("code.Person");//获取字节码
		Person p = (Person)clazz.newInstance();
		p.name = "zs";
		p.age = 12;
		p.show();
		
		//2.通过构造器创建对象
		Constructor c = clazz.getConstructor(String.class,Integer.class);
		Person p2 = (Person)c.newInstance("kl",90);
		p2.show();		
	} 
}
package code;

public class Person {
	String name;
	Integer age;
	public Person() {
		super();
	}
	
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	public void show(){
		System.out.println("name:"+name+" ,age:"+age);
	}
}

通过反射获取对象:

//获取公共字段
Field f = clazz.getField("name");
f.set(p, "uououo");
		
//获取私有字段
Field f2 = clazz.getDeclaredField("gender");
//去除私有权限
f2.setAccessible(true);
f2.set(p, "女");
p.show();

猜你喜欢

转载自blog.csdn.net/qzcrystal/article/details/82952984