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));
}
}
网友评论