package com.sadhu;
import java.util.*;
import java.lang.reflect.*;
/**
*/
public class Sample
{
public static void main(String[] args)throws Exception
{
Class cl = Class.forName("com.sadhu.ReflectTest");
Object rt = cl.newInstance();//创建一个对象
Field[] field = cl.getDeclaredFields();
for(Field item : field)
{
item.setAccessible(true);//值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。
if(item.getType() == String.class)
{
item.set(rt,"张三");
}
if(item.getType() == int.class)
{
item.set(rt,10);
}
System.out.println(item.get(rt));//输出当前字段在对象中的值是多少
}
}
}
class ReflectTest
{
private String name;
private int age;
public void setName(String aName)
{
this.name = aName;
}
public String getName()
{
return this.name;
}
public void setAge(int aAge)
{
this.age = aAge;
}
public int getAge()
{
return this.age;
}
public ReflectTest()
{
System.out.println("调用无参数构造函数!");
}
}
/**
输出结果:
调用无参数构造函数!
张三
10
*/
原文地址:http://my.oschina.net/Sadhu/blog/294126