首页 > 解决方案 > 关于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,我通过使用反射和动态代理了解了编码。但是当我尝试编码时,我发现我做不到......

[1]:https://i.stack.imgur.com/w7nKS.jpg

标签: java

解决方案


那这个呢?

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

推荐阅读