D****6 发帖数: 278 | 1 public class A {
private static class B {
public static final String password = "1234567";
}
}
怎样获取password? 如果B是个Field就好办了,就算是private也可以用
field.setAccessble(true);
可是对于private member class好像就没什么办法了?? |
c*****t 发帖数: 1879 | 2 The class is not A, but A.B.
In Java, inner classes are just like any regular classes.
【在 D****6 的大作中提到】 : public class A { : : private static class B { : public static final String password = "1234567"; : } : } : 怎样获取password? 如果B是个Field就好办了,就算是private也可以用 : field.setAccessble(true); : 可是对于private member class好像就没什么办法了??
|
r*****l 发帖数: 2859 | 3 Based on the following paragraph from Oracle, I think access private class
using reflection is not possible, unless you are doing that within the
declaring outer class.
"Tip: An access restriction exists which prevents reflective invocation of
constructors which normally would not be accessible via direct invocation. (
This includes---but is not limited to---private constructors in a separate
class and public constructors in a separate private class.) However,
Constructor is declared to extend AccessibleObject which provides the
ability to suppress this check via AccessibleObject.setAccessible(). "
【在 D****6 的大作中提到】 : public class A { : : private static class B { : public static final String password = "1234567"; : } : } : 怎样获取password? 如果B是个Field就好办了,就算是private也可以用 : field.setAccessble(true); : 可是对于private member class好像就没什么办法了??
|
r*****l 发帖数: 2859 | 4 Well, you may be able to do it using java instrument. I am too lazy to do a
test though.
(
【在 r*****l 的大作中提到】 : Based on the following paragraph from Oracle, I think access private class : using reflection is not possible, unless you are doing that within the : declaring outer class. : "Tip: An access restriction exists which prevents reflective invocation of : constructors which normally would not be accessible via direct invocation. ( : This includes---but is not limited to---private constructors in a separate : class and public constructors in a separate private class.) However, : Constructor is declared to extend AccessibleObject which provides the : ability to suppress this check via AccessibleObject.setAccessible(). "
|
x*****p 发帖数: 1707 | 5 Class c = A.class.getDeclaredClasses()[0];
Field f = c.getDeclaredField("password");
System.out.println(f.get(null)); |
r*****l 发帖数: 2859 | 6 不好好看题。B是private。Call getDeclaredFields的时候就会有
IllegalAccessException了。
【在 x*****p 的大作中提到】 : Class c = A.class.getDeclaredClasses()[0]; : Field f = c.getDeclaredField("password"); : System.out.println(f.get(null));
|
x*****p 发帖数: 1707 | 7 No way.
The code works perfectly. Do not justify by your understanding, running
result is number 1.
【在 r*****l 的大作中提到】 : 不好好看题。B是private。Call getDeclaredFields的时候就会有 : IllegalAccessException了。
|
r*****l 发帖数: 2859 | 8 oops, you are right. The result is 1234567 tough.
【在 x*****p 的大作中提到】 : No way. : The code works perfectly. Do not justify by your understanding, running : result is number 1.
|