java反射对象方法

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));
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容