美文网首页
java反射对象方法

java反射对象方法

作者: omengye | 来源:发表于2015-08-21 22:53 被阅读21次
    package algorithms;
    
    import java.lang.reflect.Method;
    
    public class Refract {
        
        public class TestClass {
            private String value;
            
            public String getValue() {
                return value;
            }
            public void setValue(String value) {
                this.value = value;
            }
        }
        
        public String getZz(Object obj) {
            Class<? extends Object> clz = obj.getClass();
            String res = "";
            try {
                Method method = clz.getMethod("getValue", new Class[]{});
                if (method.invoke(obj) != null) {
                    res = (String) method.invoke(obj);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            return res;
        }
        
        public void setZz(Object obj, String value) {
            Class<? extends Object> clz = obj.getClass();
            try {
                Method method = clz.getMethod("setValue", new Class[]{String.class});
                method.invoke(obj,value);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        
        public static void main(String[] args) {
            Refract ref = new Refract();
            TestClass node = ref.new TestClass();
            ref.setZz(node, "ok");
            System.out.println(ref.getZz(node));
        }
    }
    
    

    相关文章

      网友评论

          本文标题:java反射对象方法

          本文链接:https://www.haomeiwen.com/subject/ybbgqttx.html