I am trying to load a Java file to my android project using URLClassLoader
class.
But I got a ClassNotFoundError
when I run the below code:
package com.xyz.abc;
public class ConstantClassReader
{
public void readFile() throws MalformedURLException
{
String url = "file://"+Environment.getExternalStorageDirectory().getPath()+"/StringConstants.class";
URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[]{new URL(url)});
Class simpleClass = null;
try {
simpleClass = urlClassLoader.loadClass("com.xyz.abc.StringConstants");
Constructor simpleConstructor = simpleClass.getConstructor();
Object simpleClassObj = simpleConstructor.newInstance();
Method method = simpleClass.getMethod("myMethod");
method.invoke(simpleClassObj);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
The below Java file is resides inside my SDCard:
package com.xyz.abc;
public class StringConstants{
public void myMethod(){
System.out.println("myMethod Loaded");
}
}
A class loader loads classes .
Putting a Java source file somewhere will not do.
You have to compile that file; and maybe you are lucky then. But I would be rather surprised if the Android JVM allows you to load classes from arbitrary places. This screams: "security problem" all over the place.
Given your requirement, I would suggest a different solution, something on top of ordinary Java properties. Meaning: it seems that you simply want to provide some "configuration" information dynamically to your Java app. Then have that app read a properties file that contains key/value pairs. That is (almost) business as usual; and not leading to a need to load class files in arbitrary places.
you can embed beanshell, load the java file, instance and execute whatever.
access the java file as any other plain file from the sd
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.