在同一个包中访问私有内部类 [英] Accessing private inner class in the same package

查看:208
本文介绍了在同一个包中访问私有内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个编译单元:

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();
        }
    }
}

如果它们是相同的包,一切正常,打印response:testing123。如果它们在单独的包中,则抛出IllegalAccessException。

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

据我所知,抛出异常是因为CallingClass无法调用私有的InnerClass方法。但我不明白为什么在同一个包中允许它? InnerClass不受包保护。即使它在同一个包中,也不应在OuterClass外看到Private。我理解错了吗?

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?

推荐答案

javap 内部类的签名:

class modifiers.OuterClass$InnerClass extends java.lang.Object{
    final modifiers.OuterClass this$0;
    public java.lang.String test();
}

当谈到字节码(即运行时)时,没有这样的东西私人课程。这是编译器维护的虚构。对于反射API,有一个包可访问类型,带有公共成员方法。

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.

实际访问修饰符在 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. 

这篇关于在同一个包中访问私有内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆