使用反射从jar包中调用类的方法

时间:2013-05-29 08:01:48

标签: java class reflection jar invoke

我想使用反射从外部jar中调用类的方法。但我仍然无法做到这一点。我正在使用以下代码

public class Test {
  public static void main(String[] args) throws Exception {

    try {
      // File JarFile = new File("C:\\dataRetrieval.jar");
      //
      // URLClassLoader cl = new URLClassLoader(new
      // URL[]{JarFile.toURI().toURL()});
      // JarFile.getClass();

      DataRetrievalManagerServiceStub stub = new DataRetrievalManagerServiceStub(
           "html//...............???wsdl");
      Map<String, String> requestMap = new HashMap<String, String>();
      requestMap.put("TelephoneNumber", "01028824332");


      Object stubInstance = Class.forName("com.test.DataRetrievalManagerServiceStub").newInstance();
      Object reqInstance = Class.forName("com.test.impl.GetOllehIdsForUserDocumentImpl").newInstance();




      Method[] stubMethods = stubInstance.getClass().getMethods();
      Method[] reqMethods = reqInstance.getClass().getMethods();
      //Method[] resMethods = resInterface.getClass().getMethods();
      for (Method method : reqMethods) {
        String methodName = method.getName();
        System.out.println(methodName);

      }


      for (Method method : reqMethods) {
        String methodName = method.getName(); 
        if (methodName.startsWith("set")) {
          methodName = methodName.replace("set", "");
          String value = null;
          if (requestMap.containsKey(methodName)) {
            value = requestMap.get(methodName);
          }
          method.invoke(reqInstance, value);
        }
      }
     Object resInterface = Class.forName(
          "com.test.GetOllehIdsForUserResponseDocument").getInterfaces();


    } catch (AxisFault e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }
}

我收到如下错误消息:

log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisOperation). log4j:WARN Please initialize the log4j system properly.

Exception in thread "main" java.lang.InstantiationException: com.kt.sdp.impl.GetOllehIdsForUserDocumentImpl 
at java.lang.Class.newInstance0(Unknown Source) 
at java.lang.Class.newInstance(Unknown Source) at sdk.kt.com.Test.main(Test.java:78)

有没有人有任何想法?

0 个答案:

没有答案