I must be missing something here, but I seem to be having some trouble doing some basic reflection. I thought that due to things like boxing that I would receive true for each of the two prints below. Here is the simple Main class:
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());
}
}
}
}
Here is the class I am running it against:
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; }
}
Here is the output I receive:
Field Class: int instanceOf: false Value Class: java.lang.Integer
Field Class: java.lang.Integer instanceOf: true Value Class: java.lang.Integer
Is there a different method I should be using to determine this? isAssignableFrom also returns false for the primitive.