java跨包访问内部类,在同一个包中访问私有内部类

I have two compilation units:

public class OuterClass{

private static class InnerClass{

public String test(){

return "testing123";

}

}

public static void main( String[] args ){

new CallingClass().test( new InnerClass() );

}

}

public class CallingClass{

public void test( Object o ){

try{

Method m = o.getClass().getMethod( "test" );

Object response = m.invoke( o );

System.out.println( "response: " + response );

}

catch( Exception e ){

e.printStackTrace();

}

}

}

If they are in the same package, everything works and "response: testing123" is printed. If they are in separate packages, IllegalAccessException is thrown.

As I understand, exception is thrown because CallingClass cannot invoke private InnerClass methods. But what I do not understand is why is it allowed in the same package? InnerClass is not package protected. Private should not be visible outside OuterClass even if it is in the same package. Do I understand something wrong?

解决方案

The javap signature for an inner class:

class modifiers.OuterClass$InnerClass extends java.lang.Object{

final modifiers.OuterClass this$0;

public java.lang.String test();

}

When it comes to bytecode (i.e. runtime) there is no such thing as a private class. This is a fiction maintained by the compiler. To the reflection API, there's a package-accessible type with a public member method.

Actual access modifiers are defined in the JVM spec:

Flag Name Value Interpretation

ACC_PUBLIC 0x0001 Declared public; may be accessed from outside its package.

ACC_FINAL 0x0010 Declared final; no subclasses allowed.

ACC_SUPER 0x0020 Treat superclass methods specially when invoked by the

invokespecial instruction.

ACC_INTERFACE 0x0200 Is an interface, not a class.

ACC_ABSTRACT 0x0400 Declared abstract; may not be instantiated.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值