How can get an instance from .class file in java

痴心易碎 提交于 2020-02-03 12:23:13

问题


Frankly, I do not know even it is possible or not. But what I am trying to do is just like below.

  1. I made a class file from ClassFile.java via javac command in terminal.
  2. Then I want to get an instance from .java file or .class file.
  3. Next, I made another project in eclipse, As you guess this project path and upper file path are completely different. For instance, ClassFile.java/class file can be located in '~/Downloads' folder, the other hand, new eclipse project can be in '~/workspace/'.
  4. So I read file which referred in step 1 by FileInputStream.
  5. From here, I just paste my code.

    public class Main {

    private static final String CLASS_FILE_PATH = 
            "/Users/juneyoungoh/Downloads/ClassFile.class";
    
    private static final String JAVA_FILE_PATH = 
            "/Users/juneyoungoh/Downloads/ClassFile.java";
    
    private static Class getClassFromFile(File classFile) throws Exception {
        System.out.println("get class from file : [" + classFile.getCanonicalPath() + " ]");
        Object primativeClz = new Object();
        ObjectInputStream ois = null;
        ois = new ObjectInputStream(new FileInputStream(classFile));
        primativeClz = ois.readObject();
        ois.close();
        return primativeClz.getClass();
    }
    
    public static void main(String[] args) throws Exception {
        getClassInfo(getClassFromFile(new File(CLASS_FILE_PATH)));
    }
    

    }

just like your assumption, this code has errors. For example, it shows :

java.io.StreamCurruptedException: invalid stream header : CAFEBABE

this there any way to get object instance from .class file or .java file?

P.S. I wish do not use extra libraries.


回答1:


private static final String CLASS_FOLDER =
        "/Users/juneyoungoh/Downloads/";

private static Class getClassFromFile(String fullClassName) throws Exception {
    URLClassLoader loader = new URLClassLoader(new URL[] {
            new URL("file://" + CLASS_FOLDER)
    });
    return loader.loadClass(fullClassName);
}

public static void main( String[] args ) throws Exception {
    System.out.println((getClassFromFile("ClassFile"));
}


来源:https://stackoverflow.com/questions/21258032/how-can-get-an-instance-from-class-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!