我正在尝试创建一个 java 学习 android 应用程序。它应该有一个供用户使用的代码游乐场;可以运行简单的java代码。我将用户代码保存在 java 代码中并尝试运行它。我正在使用 JANINO ,但问题是我无法加载包括用户代码在内的外部类。这是我的代码;
String UsersCodeInput;
public void Run() throws FileNotFoundException, IOException
{
File sourcepath = new File(Environment.getExternalStorageDirectory()+"/MainFolder");
File JavaFile = new File(sourcepath.getPath()+"A.java");
FileOutputStream fos = new FileOutputStream(JavaFile);
fos.write(UsersCodeInput.getBytes());
fos.close();
// now Users Code is Saved.
//trying to run it by means of janino :
ClassLoader cl = new JavaSourceClassLoader(
this.getClass().getClassLoader(), // parentClassLoader
new File[] {sourcepath}, //our sourceFolder
"UTF-8" //Encodeing
);
try
{
// problem is here. next line is not working well; throws classNotFound.
Object o = cl.loadClass(".A").newInstance();
//the class implements runnable.
((Runnable) o).run();
}
catch (ClassNotFoundException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
catch (InstantiationException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
catch (IllegalAccessException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
}
这是 JANINOs 教程;阅读“源代码编译器”部分 http://janino-compiler.github.io/janino/
谢谢。