我有一个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
方法中,它从对象参数获取有关接口中方法声明的信息。
我不确定这是否提供了足够的上下文,但如果还不够,我在此处提出的另一个问题还有更多细节:Using JET to generate code: Indenting code
感谢。
答案 0 :(得分:3)
如果我了解您要做的事情,您应该可以使用dynamic proxying将其删除。下面是在运行时实现接口而不明确知道接口类型的示例:
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();
}
}