gpt4 book ai didi

java - 动态对象的反射方法调用

转载 作者:行者123 更新时间:2023-12-02 12:00:54 24 4
gpt4 key购买 nike

我正在 java 应用程序的运行时创建一个类(名为 haan.java)。 此类的对象插入到 Oracle Coherence Cache 中 当我从缓存中获取一个对象(tempHaan)时,它的类型是haan。但是当我尝试调用此对象(tempHaan)的方法时,我收到错误“java.lang.IllegalArgumentException:对象不是声明类的实例”

“Object invoke = methodgetHash.invoke(tempHaan, null);”行发生错误

PFB the code:

NamedCache cacheConn;
CacheFactory.ensureCluster();
NamedCache cacheConnHaan = CacheFactory.getCache("Haan");
Class cls = null;
File f = new File(rtomProperties.getPropertyValue("pojoToBuild"));

try {
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader cl = new URLClassLoader(new URL[] { f.toURI().toURL() },
currentThreadClassLoader);
Object tempHaan;
cls = Class.forName(rtomProperties.getPropertyValue("pojoPackageLocation").concat(".haan"), true, cl);
System.out.println("*************** the class is **********"
+ cls.newInstance().getClass().toString());
System.out.println("******DONE LOADING");

URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class clazz = URLClassLoader.class;

// Use reflection
Method m = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
URL ur = f.toURI().toURL();
m.invoke(classLoader, new Object[] { ur });

Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");

tempHaan = cacheConnHaan.get(aan);

System.out.println("*************AFTER" + tempHaan.getClass().toString());

System.out.println("*************tempHaan: "+tempHaan.toString());
Class[] paramObject = new Class[1];
paramObject[0] = Object.class;
Method methodgetHash = null;
Class noparams[] = {};
methodgetHash = cls.getDeclaredMethod("getHash", noparams);
Object temp = cls.newInstance();

Object invoke = methodgetHash.invoke(tempHaan, null);
key = (String) invoke;

System.out.println("key for the record: " + key);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
System.out.println("******not instantiated");
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("Hash-Aan mapping not found for aan " + aan);
continue;
}

最佳答案

您动态创建一个 ULRClassLoader 来加载类,即缓存实例的类和您从中获取要调用的方法的类来自不同的类加载器,从而导致此错误。您可以从要缓存的实例中获取声明的方法并将其与实例一起缓存,或者从缓存中检索实例并通过调用获取要调用的方法

Method methodgetHash = tempHaan.getDeclaredMethod("getHash", noparams);

将方法与要缓存的类一起缓存将会带来性能的改进。

关于java - 动态对象的反射方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com