【发布时间】:2017-11-14 19:22:41
【问题描述】:
我正在我的 java 应用程序运行时创建一个类(名为 haan.java)。 此类的对象被插入到 Oracle Coherence 缓存中 当我从缓存中获取一个对象(tempHaan)时,它的类型是 haan。但是当我尝试调用这个对象(tempHaan)的方法时,我收到错误 "java.lang.IllegalArgumentException: object is not an instance of declaring class"
“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;
}
【问题讨论】:
-
这一切的原因是什么?这似乎过于复杂和毫无意义。
标签: java reflection