package com.org.reflect;
import java.lang.reflect.Field;
import org.junit.Test;
/**
* 反射字段
* @author Administrator
*
*/
public class Ref3 {
//反射方法:public String name="hello,summer";
@Test
public void test1() throws Exception
{
Student stu=new Student();
Class clazz = Class.forName("com.org.reflect.Student");
Field field = clazz.getField("name");//获取字段名
String name=(String) field.get(stu);//获取哪个对象字段上的名字
System.out.println(name);
field.set(stu, "1234");
System.out.println(stu.name);
}
//反射方法:private String classNo="2011211221";
@Test
public void test2() throws Exception
{
Student stu=new Student();
Class clazz = Class.forName("com.org.reflect.Student");
Field f = clazz.getDeclaredField("classNo");
f.setAccessible(true);
String classNo = (String)f.get(stu);
System.out.println(classNo);
}
//反射方法:private static int age=123;
@Test
public void test3() throws Exception
{
//Student stu=new Student();
Class clazz = Class.forName("com.org.reflect.Student");
Field f = clazz.getDeclaredField("age");
f.setAccessible(true);
/**
* If the underlying(相关) field is a static field,
* the <code>obj</code> argument
is ignored(忽视); it may be null.
*/
int age = (Integer)f.get(null);
System.out.println(age);
}
}
import java.lang.reflect.Field;
import org.junit.Test;
/**
* 反射字段
* @author Administrator
*
*/
public class Ref3 {
//反射方法:public String name="hello,summer";
@Test
public void test1() throws Exception
{
Student stu=new Student();
Class clazz = Class.forName("com.org.reflect.Student");
Field field = clazz.getField("name");//获取字段名
String name=(String) field.get(stu);//获取哪个对象字段上的名字
System.out.println(name);
field.set(stu, "1234");
System.out.println(stu.name);
}
//反射方法:private String classNo="2011211221";
@Test
public void test2() throws Exception
{
Student stu=new Student();
Class clazz = Class.forName("com.org.reflect.Student");
Field f = clazz.getDeclaredField("classNo");
f.setAccessible(true);
String classNo = (String)f.get(stu);
System.out.println(classNo);
}
//反射方法:private static int age=123;
@Test
public void test3() throws Exception
{
//Student stu=new Student();
Class clazz = Class.forName("com.org.reflect.Student");
Field f = clazz.getDeclaredField("age");
f.setAccessible(true);
/**
* If the underlying(相关) field is a static field,
* the <code>obj</code> argument
is ignored(忽视); it may be null.
*/
int age = (Integer)f.get(null);
System.out.println(age);
}
}