Sco*_*ott 1 java reflection primitive-types
我必须在这里遗漏一些东西,但我似乎在做一些基本的反思时遇到了麻烦.我认为,由于像拳击这样的东西,我会收到以下两个印刷品中的每一个.这是简单的Main类:
package com.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestingReflection {
public static void main(String[] args) throws SecurityException,
NoSuchMethodException,
IllegalArgumentException,
IllegalAccessException,
InvocationTargetException
{
final Class c = Reflection.class;
Reflection p = new Reflection();
p.setIntObj(new Integer(1));
p.setIntPrim(1);
for (Field field : c.getDeclaredFields()) {
char first = Character.toUpperCase(field.getName().charAt(0));
String capitalized = first + field.getName().substring(1);
Method getField =
c.getDeclaredMethod("get" + capitalized, new Class [] {});
Class fieldClass = getField.getReturnType();
Method setField =
c.getDeclaredMethod("set" + capitalized,
new Class [] { fieldClass });
Object value = getField.invoke(p, new Object [] {});
if (value != null) {
System.out.println("Field Class: "
+ fieldClass.getName()
+ " instanceOf: "
+ fieldClass.isInstance(value)
+ " Value Class: "
+ value.getClass().getName());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我正在运行它的类:
package com.reflection;
public class Reflection {
private int intPrim;
private Integer intObj;
public int getIntPrim() { return intPrim; }
public void setIntPrim(int intPrim) { this.intPrim = intPrim; }
public Integer getIntObj() { return intObj; }
public void setIntObj(Integer intObj) { this.intObj = intObj; }
}
Run Code Online (Sandbox Code Playgroud)
这是我收到的输出:
Field Class: int instanceOf: false Value Class: java.lang.Integer
Field Class: java.lang.Integer instanceOf: true Value Class: java.lang.Integer
Run Code Online (Sandbox Code Playgroud)
我应该使用不同的方法来确定这个吗?isAssignableFrom也为原语返回false.
获取原始类型的最简单方法int是int.class你也可以使用,Integer.TYPE但我相信这是为了向后兼容.
Java doc Class.isIntanceof(Object)说
如果此Class对象表示基本类型,则此方法返回false.
这可能不是一个有用的定义,但它是它的工作方式.我还没有找到一种简单的方法来获取基本类型的包装类,所以我使用了预定义的HashMap(它有9个类,包括void)
| 归档时间: |
|
| 查看次数: |
5196 次 |
| 最近记录: |