簡體   English   中英

沒有實現類的接口的實例

[英]Instance of an interface without an implementation class

我有一個JET模板,旨在為接口實現類生成代碼。 我無法提出一個可執行的測試類來打印出此生成的代碼,因為我無法從JET模板創建的generate方法的參數獲取對象。

我希望測試類能夠像這樣工作:

/**
 * An executable test class that prints out exemplary generator output
 * and demonstrates that the JET template does what it should.
 */
public class TestClass {
    public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        String className = "A"; // "A" is the name of the interface in the same package.

        Class c = Class.forName(className);
        Object o = c.newInstance();

        Q2Generator g = new Q2Generator(); // Class created from the JET Template
        String result = g.generate(o);
        System.out.println(result);
    }
}

但顯然, c.newInstance(); 不適用於界面。 有沒有其他方法可以將接口的對象提供給generate方法? 我需要接口的對象,因為在Q2Generator的generate方法中,它從object參數獲取有關接口中方法聲明的信息。

我不確定是否可以提供足夠的上下文,但是如果還不夠,我在這里問的另一個問題還有更多詳細信息: 使用JET生成代碼:縮進代碼

謝謝。

如果我了解您要執行的操作,則應該可以使用動態代理將其實現。 這是一個在運行時實現接口而無需顯式知道接口類型的示例:

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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM