Daniel
Daniel

Reputation: 21

How can I read Class and objects name from File using Java Reflection?

I have a file named Objects.dat and I want to read the Class name and objects name from that file using Java Reflection. I'm able to read from another Java class but not from the file. How can I solve this?

Java Class

public class EmployeeInfo {
    private String username = "John";
    private int userage = 23;
}

Objects.dat contains the same text as Java class.

Class Reader

public class FileRd {
    public static void main(String[] args)  {
            try {
                Class cls = Class.forName("EmployeeInfo");
                Object obj = cls.newInstance();

                System.out.println("Class Name-->"+obj.getClass());
                Field[] fields = cls.getDeclaredFields();
                for( int i = 0 ; i < fields.length ; i++ ) {
                    fields[i].setAccessible(true);
                    System.out.println("Name-->"+fields[i].getName());
                }
            }
            catch( Exception e ) { e.printStackTrace(); }
    }
}

The above code works for the Java class but I want to input the file like and read -

FileInputStream fin = new FileInputStream("D:\\Objects.bat");

and perform the above functionally but I failed to do that.

Upvotes: 2

Views: 940

Answers (2)

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

You need a Custom classloader for such, if the file is already compiled (if not you can use javac tool to compile it with classpath or an Bytecode tool like ASM or Javassist).

Then you use your ClassLoader to load the file(.class) and findClass.

Upvotes: 1

Jackkobec
Jackkobec

Reputation: 6765

Maybe Serialization / Deserialization is the better way than save Java code at the file.

Upvotes: 0

Related Questions