无法通过java反射调用方法:NoSuchMethodException [英] Unable to invoke method by java reflection: NoSuchMethodException

查看:190
本文介绍了无法通过java反射调用方法:NoSuchMethodException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发一个动态类加载器项目,并尝试通过URLClassLoader在动态加载的类中调用一个方法。它在Eclipse中运行时效果很好,所以调用和动态加载的类被捆绑到两个不同的jar中,然后部署到Server中,因为它是分为两个jar的一部分。调用 mapClass.getDeclaredMethod(run,oneParam)

We are working on a dynamic class loader project and trying to invoke a method in a dynamically loaded class via URLClassLoader. It works pretty well when it's run in Eclipse, so the invoking and dynamically loaded classes are bundled in to two different jars then deployed into Server because it’s part of requirement to split into two jars.

NoSuchMethodException / code>使用反射api。

NoSuchMethodException exception thrown when calling mapClass.getDeclaredMethod("run", oneParam) using reflection api.

我们已经验证了Jar,它确认了被调用的方法存在于类中。

We have verified Jar and it confirms methods being invoked is present in class.

以下是示例代码..

import com.altova.io.Input; 
import com.altova.io.FileInput;

Input sourceInput = new FileInput(inputFileFullPath);

Class oneParam[] = { Input.class };
Object mapObj = mapClass.newInstance();
Method method = mapClass.getDeclaredMethod(RUN, oneParam);
li = (List) method.invoke(mapObj, sourceInput);

异常

java.lang.NoSuchMethodException:      
    com.sample.test.TrackingService.run(com.altova.io.Input)

只有区别我怀疑是输入(在方法签名中)和FileInput(在参数中)。

Only difference I doubt is Input(in method signature) and FileInput (in the parameter).

它在Eclipse中运行良好,但不在服务器中。它采用JDK 1.6& 1.7,但服务器运行在jdk 1.7

It works well in Eclipse, but not in server. It's tested with JDK 1.6 & 1.7, but server runs on jdk 1.7

第二个选项..尝试如下所示,但这次它抛出

Second option.. tried as shown below but this time it throws

java.lang.IllegalArgumentException:参数类型不匹配

代码

for (Method method : mapClass.getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().equals("run")) {
    Class<?>[] params = method.getParameterTypes();
    if (params.length == 2) {
        if (params[0].isInstance(sourceInput) && params[1].isInstance(outputStream)) {
            li = (List<ByteArrayOutputStream>) method.invoke(mapObj, sourceInput, outputStream);
            System.out.println(" Parsing is complete:");
        }
    }
}}


推荐答案

当类装载器改变如下所示时,它起作用。

It worked when the class loader changed as shown below.

URLClassLoader loader = new URLClassLoader(new URL [] {new URL (file:/opt/jars/Tracking.jar)},this.getClass()。getClassLoader());

休息一切都一样...正如我所说,在eclipse中运行时,加上当前的类加载器也是有效的。

Rest everything same... as I said, with-out adding the current class loader also worked when run in eclipse.

这篇关于无法通过java反射调用方法:NoSuchMethodException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆