java反射
public void f(int i)
public void f(Integer i)
我想用反射来写个通用的方法来执行上面的方法
public static void invokeMethod(Object obj,String methodName,int i){
Class sourceType = obj.getClass();
Class paramType = //这边怎么判定参数类型是int,还是Integer
Method method = sourceType.getDeclaredMethod(methodName, paramType);
}
[解决办法]
if(参数.class.isPrimitive()){
是基本类型
}else{
是封装类型
}
[解决办法]
if (fields instanceof type) {
type new_name = (type) fields;
}或者
反射判断呢
public class Tongxun {
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Foo foo = new Foo();
Class clazz = foo.getClass();
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (field.getType() == Integer.class) {
Method m2 = clazz.getDeclaredMethod("f", Integer.class);
m2.invoke(foo, 43454);
System.out.println("--Integer--");
}
if (field.getType() == int.class) {
Method m1 = clazz.getDeclaredMethod("f", int.class);
m1.invoke(foo, 12);
System.out.println("--int--");
}
}
}
}
class Foo {
public int x;
public Integer y;
public void f(int x) {
System.out.print(x);
}
public void f(Integer y) {
System.out.print(y);
}
}