1. 程式人生 > >獲取位元組碼 建立物件

獲取位元組碼 建立物件

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();