简体   繁体   English

如何访问Android中SDCard内的Java文件

[英]How to access java file which resides inside SDCard in Android

I am trying to load a Java file to my android project using URLClassLoader class. 我正在尝试使用URLClassLoader类将Java文件加载到我的android项目中。

But I got a ClassNotFoundError when I run the below code: 但是运行以下代码时出现ClassNotFoundError

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: 下面的Java文件位于我的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. 将Java源文件放在某处不会。

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. 但是,如果Android JVM允许您从任意位置加载类,我会感到非常惊讶。 This screams: "security problem" all over the place. 尖叫:“安全问题”到处都是。

Given your requirement, I would suggest a different solution, something on top of ordinary Java properties. 根据您的要求,我建议使用其他解决方案,除了普通的Java属性之外。 Meaning: it seems that you simply want to provide some "configuration" information dynamically to your Java app. 含义:似乎您只是想向Java应用程序动态提供一些“配置”信息。 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. 而不需要将类文件加载到任意位置。

http://www.beanshell.org/ http://www.beanshell.org/

you can embed beanshell, load the java file, instance and execute whatever. 您可以嵌入beanshell,加载Java文件,实例并执行任何操作。

access the java file as any other plain file from the sd 从sd像访问其他任何普通文件一样访问java文件

How can I read a text file from the SD card in Android? 如何在Android中从SD卡读取文本文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM