2013年9月23日星期一

Reflection to invoke setter / getter method a small problem

Watching "java development real classic" reflection chapter , invoked by reflection setter and getter, my own experiments encountered a problem , how the return value of the getter to return ?
code book is this:

public static void setter(Object obj,String att,Object value,Class<?>type){
try{
Method met = obj.getClass().getMethod("set"+initStr(att),type);
met.invoke(obj, value);
}catch(Exception e){
e.printStackTrace();
}
}
public static void getter(Object obj,String att){
try{
Method met = obj.getClass().getMethod("get"+initStr(att));
System.out.println(met.invoke(obj));
}catch(Exception e){
e.printStackTrace();
}
return temp;
}

I want to return the getter method return value , write how not ah ?

public static Object getter(Object obj,String att){
try{
Method met = obj.getClass().getMethod("get"+initStr(att));
Object temp = met.invoke(obj);
}catch(Exception e){
e.printStackTrace();
}
return temp;
}

invoke methods do not have a return value ?
------ Solution ---------------------------------------- ----
try{
            Method met = obj.getClass().getMethod("get"+initStr(att));
            Object temp = met.invoke(obj);
        }catch(Exception e){
            e.printStackTrace();
        }
        return temp;
改为
 Object temp=null;
try{
            Method met = obj.getClass().getMethod("get"+initStr(att));
            temp = met.invoke(obj);//这里定义是局部变量,return娶不到的。
        }catch(Exception e){
            e.printStackTrace();
        }
        return temp;

------ For reference only ----------------------------------- ----
Thank you, understand

没有评论:

发表评论