java如何获取调用者的实例
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws
SecurityException, NoSuchFieldException,
ClassNotFoundException,
IllegalArgumentException,
IllegalAccessException {
A test=new A();
test.getC();
}
}
class A{
public String a="aaaaaaaashort";
private String b="short";
public String getC() throws SecurityException, NoSuchFieldException, Class
NotFoundException, IllegalArgumentException, IllegalAccessException{
B b=new B();
return b.getthisC();
}
}
class B{
public String c="ccccccccc";
public String getthisC() throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
StackTraceElement stack[] = Thread.currentThread().getStackTrace();
System.out.println(stack[1].getClassName());
Class ownerClass1 = Class.forName(stack[1].getClass().getName());
Field f = ownerClass1.getDeclaredField("c");
Object fv = f.get(ownerClass1);
System.out.println(fv.toString());
return c;
}
}
如何获取到b实例对象,获取到b实例中的c属性?
java
反射
------解决方案-------------------- public static String c = "ccccccccc";
Class ownerClass1 = Class.forName(stack[1].getClassName());
stack[1]是StackTraceElement的类对象,你之前得到的类就不是B了
Object fv = f.get(ownerClass1);
这句你用Class直接传参,那你的String就要声明为类对象,
要不你就把ownerClass1替换成ownerClass1.newInstance()