没有实现类的接口实例

我有一个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(); } }