How can get an instance from .class file in java

2019-07-23 14:26发布

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条回答
【Aperson】
2楼-- · 2019-07-23 14:37
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"));
}
查看更多
登录 后发表回答