反射简单测试

package com.gyarmy.person;

import java.lang.reflect.Field;

import org.junit.Test;

public class TestPerson {

	@Test
	public void test2() throws Exception{
		Class cls1  = Class.forName("com.gyarmy.person.Person");
		Field nameField = cls1.getDeclaredField("name");
		//打开访问权限
		nameField.setAccessible(true);
		Person p1 = new Person();
		nameField.set(p1, "百度");
		
		System.out.println(p1.getName());
	}
	
	
	//测试反射
	@Test
	public void test1() throws ClassNotFoundException{
		//互殴字节码
		Class cls1 = Class.forName("com.gyarmy.person.Person");
		Class cls2 = new Person().getClass();
		Class cls3 = Person.class;

		System.out.println("cls1 = "+cls1);
		System.out.println("cls2 = "+cls2);
		System.out.println("cls3 = "+cls3);
		
	}
	
	
	
	
}

原文链接: 反射简单测试 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-77.html )

发表评论

0则评论给“反射简单测试”