这个例子搞清楚了,就能对java反射机制用法有一个清晰的概念了。
Test4.java:
package com.wy.ref.test4;
import java.lang.reflect.*;
import java.util.ArrayList;
public class Test4
{
public static void main(String[] args)
{
Test4 t = new Test4();
t.run();
}
public void run()
{
Template tp = new Template();
tp.a = 1;
tp.b = false;
tp.c = "ABC";
Field[] field;
Class<?> c = tp.getClass();
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> type = new ArrayList<String>();
try
{
field = c.getFields();
for (int i = 0; i < field.length; i++)
{
name.add(field[i].getName());
type.add(field[i].getType().getSimpleName());
}
System.out.println(name.toString());
System.out.println(type.toString());
for(int i=0;i<field.length;i++)
{
Field actionField = c.getField(name.get(i));
Object value = actionField.get(tp);
System.err.println(value.toString());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Template.java:
package com.wy.ref.test4;
public class Template
{
public Integer a;
public Boolean b;
public String c;
public String getC()
{
return c;
}
}