我已经通过在 toString() 方法所在的类中获取和格式化变量来设法使反射工作。
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();
}
}
但是我想知道是否可以在目录中指定一个特定文件供 toString()
处理?
我已经尝试获取一个文件并将其插入 System.out.println()
但我看到它的方式是您需要创建一个类的实例并为其提供实例它工作。所以我不确定如何以编程方式完成。
我一直在尝试这样的事情:
Path path = FileSystems.getDefault().getPath("D:\\Directory\\Foo\\Bar\\Test.java", args);
File file = path.toFile();
System.out.println(file);
但是我并没有深入了解它,我主要是看看我是否可以将文件转换成任何可用的东西,但我不确定我需要做什么!
任何建议都会很棒。
最佳答案
我认为您需要查看 ClassLoader API - 您需要获得一个新的 URLClassLoader并要求它将您的 .java 文件加载到 JVM 中。然后你可以反射(reflection)它。
关于java - 使用反射从另一个 .java 文件获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14904360/