public class Test {
// 修改方法createObject内容,实现main里面的两处打印
public static void main(String[] arges) throws Exception {
IA ia = (IA) createObject(IA.class.getName() + "$getName =Abc");
System.out.println(ia.getName()); //output: Abc
ia = (IA) createObject(IA.class.getName() + "$getName= Bcd");
System.out.println(ia.getName()); //output: Bcd
}
// please coding in createObject for true output
public static Object createObject(String str) throws Exception {
// your coding
}
interface IA {
String getName();
}
}
Through Google, I learned about coding through the use of reflection and dynamic proxies. But when I tried coding, I found that I couldn't do it...
What about this?
public class Test {
public static void main(String[] arges) throws Exception {
IA ia = (IA) createObject(IA.class.getName() + "$getName =Abc");
System.out.println(ia.getName()); //output: Abc
ia = (IA) createObject(IA.class.getName() + "$getName= Bcd");
System.out.println(ia.getName()); //output: Bcd
}
// please coding in createObject for true output
public static Object createObject(String str) throws Exception {
String[] split = str.split("\\$getName\\s?=\\s?");
String classname = split[0];
String value = split[1];
return Proxy.newProxyInstance(Class.forName(classname).getClassLoader(), new Class[] { IA.class },
(proxy, method, args) -> {
if ("getName".equals(method.getName()))
return value;
throw new Exception();
});
}
interface IA {
String getName();
}
}
Outputs:
Abc
Bcd
I would do it like this:
public static Object createObject(String str) throws Exception {
String value = str.split("=")[1].trim();
return (IA) () -> value;
}
There is not really reflection needed because we only care about the part after the equation mark.
As the class name and method name are provided in the parameter, I made no assumption on the IA interface. Everything is dynamic.
// please coding in createObject for true output
public static Object createObject(String str) throws Exception {
final String className = str.substring(0, str.lastIndexOf("$"));
final String methodName=str.substring(str.lastIndexOf("$")+1,str.indexOf("=")).trim();
final String value = str.substring(str.indexOf("=") + 1).trim();
return Proxy.newProxyInstance(Class.forName(className).getClassLoader(), new Class[] { Class.forName(className) },
(proxy, method, methodArgs) -> {
if (method.getName().equals(methodName)) {
return value;
} else {
throw new UnsupportedOperationException("Unsupported method: " + method.getName());
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.