下面是一个调用已经私有化的单列的函数的列子. 这里用了静态内部类,关键就是静态内部类可以访问外部类的私有构造函数。

这种算是变种继承吧。前提是可以在原来的单列类里添加代码。

class Single {

        private Single(){
                System.out.println("Single");
        }
        
        public void runSingleMethod()
        {
                System.out.println("runSingleMethod");
        }
        public static class Evil extends Single
        {
                public Evil(){
                        System.out.println("Evil");
                }
        }
}

public class SingleTest extends Single.Evil
{
        public SingleTest()
        {
                System.out.println("normal");
        }
        
        public static void main(String[] args) {
                SingleTest a = new SingleTest();
                a.runSingleMethod();
        }
}

output:

Single
Evil
normal
runSingleMethod

这个列子表明,要阻止继承,还是得靠关键字 final.
我不知道 可不可以用字节码增加包 比如ASM 包动态的给Single类增加上面的那段静态类代码,但是有一点在这里可以确认就是私有函数不能完全阻止继承。

相关文章:

  • 2021-09-17
  • 2021-08-20
  • 2022-12-23
  • 2022-12-23
  • 2022-02-27
  • 2021-11-03
  • 2021-10-12
  • 2022-02-23
猜你喜欢
  • 2022-12-23
  • 2022-01-28
  • 2021-12-26
  • 2021-08-14
  • 2022-12-23
  • 2021-09-21
  • 2021-08-31
相关资源
相似解决方案