2011-10-14 50 views
1

我有一個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

感謝。

回答

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

我認爲這可能有效。越來越接近現在想出一些東西。非常感謝。 – Jigglypuff

相關問題