问题
Frankly, I do not know even it is possible or not. But what I am trying to do is just like below.
- I made a class file from ClassFile.java via javac command in terminal.
- Then I want to get an instance from .java file or .class file.
- 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/'.
- So I read file which referred in step 1 by FileInputStream.
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