java - 关于Java反射的面试题
问题描述
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();
}
}
通过 Google,我通过使用反射和动态代理了解了编码。但是当我尝试编码时,我发现我做不到......
解决方案
那这个呢?
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();
}
}
输出:
Abc
Bcd
推荐阅读
- html - HTML5的CSS浮动不浮动div容器中的视频元素
- tensorflow - 我应该使用哪一个来预处理图像?
- javascript - 生产模式下的 webpack 问题(缩小问题)
- java - Spring-security 防止控制器在没有日志错误消息的情况下执行 POST
- php - 具有两列 Laravel 的同一张表上的多个关系
- javascript - php函数不写入服务器上的文件
- java - 如果字符串实际上是数字,则将百分比符号 (%) 附加到字符串
- asp.net-core - 在 _layout 和 index 页面之间的 asp.net core razor pages 中使用 asp-page 和 asp-route 的正确方法
- c++ - 如何强制 std::weak_ordering
- markdown - Gatsby & Netlify - 通过 cloudinary 添加多个图像