获得了一个类的Class后,再获取他的Field..
1.之后怎样判断他是public static final ?
2.然后用这个Field.getName()获得了这个常量的名称,怎样取出他的值?
搞了1个多小时没想出来,请教各位大侠,谢谢!
------解决方案--------------------
public class FieldReflactTest{
public static final String a="test";
protected int b;
private int c;
String d;
public static void main(String[] args){
Field[] fields=FieldReflactTest.class.getDeclaredFields();
for(Field field:fields){
String descriptor=Modifier.toString(field.getModifiers());//获得其属性的修饰
descriptor=descriptor.equals("")==true?"":descriptor+" ";
System.out.println(descriptor+field.getName()+"="+field.get(new FieldReflactTest()));
}
}
}
------解决方案--------------------
Object obj = clz.newInstance();
....
System.out.println(f.get(obj));获取实例字段//其实都可以用这个方法
------解决方案--------------------
package org.apache.commons.mvc.tag;
import java.lang.reflect.Field;
import javax.servlet.jsp.JspException;
/**
* 输出类的静态字段
* @version 2.0
*/
public class StaticFieldTag extends BaseTag {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
private Class class1;
private String name;
public int doStartTag() throws JspException {
try {
Field field1 = class1.getField(name);
if (null != field1) {
Object object = field1.get(null);
if (null != object) {
write(object.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return SKIP_BODY;
}
/**
* 类的名称(要完整的)
* @param type
*/
public void setType(String type) {
try {
class1 = Class.forName(type);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 字段的名称(要public static修饰符的)
* @param name
*/
public void setName(String name) {
this.name = name;
}
}