我有一个使用ClassLoader和Reflection来加载和调用方法的应用程序。在运行时,我收到此异常:java.lang.IllegalArgumentException : object is not an instance of declaring class
。这是我的代码:
File operatorFile = new File(OperatorsPath);
URL operatorFilePath = operatorFile.toURL();
URL[] operatorFilePaths = new URL[]{operatorFilePath};
ClassLoader operatorsLoader = new URLClassLoader(operatorFilePaths);
Class operatorInterface = operatorsLoader.loadClass("Operator");
FilenameFilter filterDotClass = new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".class");
}
};
File[] operatorFiles = new File(OperatorsPath).listFiles(filterDotClass);
Class[] operatorClass = new Class[operatorFiles.length-1];
int index = 0;
Method methodsInOperator;
Object instance;
String operatorSign;
Map<String , Object> operatorMap = new HashMap<String , Object>();
for (File oprFile : operatorFiles)
{
String filename = oprFile.getName();
//String filename = "operators."+oprFile.getName();
filename = filename.substring(0, filename.length() - 6);
Class currentClass = operatorsLoader.loadClass(filename);
if (!filename.equalsIgnoreCase("operator") && operatorInterface.isAssignableFrom(currentClass))
{
operatorClass[index] = currentClass;
instance = currentClass.newInstance();
methodsInOperator = currentClass.getMethod("getSign", null);
operatorSign = (String)methodsInOperator.invoke(instance, null);
operatorMap.put(operatorSign,instance);
++index;
}
}
while(expression != null)
{
String[] elementInExpression = expression.split(",");
if(elementInExpression.length != 3)
{
System.out.println("Expression should have two operand and 1 operator ");
throw new ValidationException("Validation on number of element failed1");
}
Validation.validateOperand(elementInExpression[0],elementInExpression[1]);
Validation.validateOperator(elementInExpression[2]);
double firstNumber = Double.parseDouble(elementInExpression[0]);
double secondNumber = Double.parseDouble(elementInExpression[1]);
double output = 0;
Object obj;
for(Class operatorCls : operatorClass)
{
obj = (Object)operatorMap.get(elementInExpression[2]);
methodsInOperator = operatorCls.getMethod("calculate", new Class[] { double.class, double.class } );
output =(double)methodsInOperator.invoke(obj, firstNumber, secondNumber);
}
processingResult.add(output);
expression = mathExpReader.readLine();
}
readerWriter.writeFile(path,processingResult);
任何人都可以帮助我吗?