SteWoo
SteWoo

Reputation: 468

Getting variables from another .java file using reflection

I've managed to get reflection working by getting and formatting the variables in the class that the toString() method is in.

public class ReadFile {

public int test1 =0;
public String test2 = "hello";
Boolean test3 = false;
int test4 = 1;

public static void main(String[] args) throws IOException{

    ReadFile test = new ReadFile();

    System.out.println(test);

}


public String toString(){

    //Make a string builder so we can build up a string
    StringBuilder result = new StringBuilder();
    //Declare a new line constant
    final String NEW_LINE = System.getProperty("line.separator");

    //Gets the name of THIS Object
    result.append(this.getClass().getName() );
    result.append(" Class {" );
    result.append(NEW_LINE);

    //Determine fields declared in this class only (no fields of superclass)
    Field[] fields = this.getClass().getDeclaredFields();

    //Print field names paired with their values
    for ( Field field : fields  ) {
        result.append("  ");
        try {
            result.append(field.getType() + " "); 
            result.append( field.getName() );
            result.append(": ");
            //requires access to private field:
            result.append( field.get(this) );
        } catch ( IllegalAccessException ex ) {
            System.out.println(ex);
        }
        result.append(NEW_LINE);
    }
    result.append("}");

    return result.toString();
}
}

However I was wondering whether it would be possible to specify a specific file in the directory for the toString() to work on?

I have tried getting a file and plugging it in the System.out.println() but the way I see it is you need to make an instance of a class and give it the instance for it to work. So I'm not sure how that can be done programatically.

I have been trying something like this:

    Path path = FileSystems.getDefault().getPath("D:\\Directory\\Foo\\Bar\\Test.java", args);

    File file = path.toFile();

    System.out.println(file);

However I don't get very far with it, I've mainly been seeing if I can convert the file into anything usable but I'm not sure what I need to be doing!

Any advice would be great.

Upvotes: 1

Views: 2254

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61198

I think you need to look into the ClassLoader API - you need to get an new URLClassLoader and ask it to load your .java file into the JVM. You can then reflect on it.

Upvotes: 2

MrSmith42
MrSmith42

Reputation: 10171

You can try to read the package information from the file (D:\Directory\Foo\Bar\Test.java) and than try to load it the class by its name:

Class.forName(nameOfTheClass)

Java API Class

Upvotes: 1

Related Questions