Instance of an interface without an implementation class

无人久伴 提交于 2019-12-04 19:40:55

If I understand what you're trying to do, you should be able to pull it off with dynamic proxying. Here's an example of implementing an interface at runtime without explicitly knowing the interface's type:

import java.lang.reflect.*;

public class ImplementInterfaceWithReflection {
    public static void main(String[] args) throws Exception {
        String interfaceName = Foo.class.getName();
        Object proxyInstance = implementInterface(interfaceName);
        Foo foo = (Foo) proxyInstance;
        System.out.println(foo.getAnInt());
        System.out.println(foo.getAString());
    }

    static Object implementInterface(String interfaceName)
            throws ClassNotFoundException {
        // Note that here we know nothing about the interface except its name
        Class clazz = Class.forName(interfaceName);
        return Proxy.newProxyInstance(
            clazz.getClassLoader(),
            new Class[]{clazz},
            new TrivialInvocationHandler());
    }

    static class TrivialInvocationHandler implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) {
            System.out.println("Method called: " + method);
            if (method.getReturnType() == Integer.TYPE) {
                return 42;
            } else {
                return "I'm a string";
            }
        }
    }

    interface Foo {
        int getAnInt();
        String getAString();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!