I was searching for how to access the private field of a class from other class and found that it can be done using reflect.Field as in the following code, but when i try to execute the code i get an error saying :Error: Could not find or load main class com.example.Test
why is it happening?
Test.java
package com.example;
import java.lang.reflect.*;
class Test
{
public static void main(String[] args)
// Just for the ease of a throwaway test. Don't
// do this normally!
throws Exception
{
Other t = new Other();
t.setStr("hi");
Field field = Other.class.getDeclaredField("str");
field.setAccessible(true);
Object value = field.get(t);
System.out.println(value);
}
}
Other.java
package com.example;
class Other
{
private String str;
public void setStr(String value)
{
str = value;
}
}
Aucun commentaire:
Enregistrer un commentaire