简体   繁体   English

Java:是否可以访问私有静态方法

[英]Java : Is it possible to access private static method

Is it possible to access the private static method within the object creation scope? 是否可以在对象创建范围内访问私有静态方法? Something like the below snippet. 类似于以下代码段。

class A {
   private static void func(int x) {
      /*Some Code here*/
   }
}

and call from another context, something like this : 然后从另一个上下文调用,如下所示:

new A(){{
  func(2);
}};

The intent here is to facilitate for addition of more calls to func(int) , with a differnt argument for each call, or to put simpler, some sort of builder for the object of type A . 这样做的目的是为了方便向func(int)添加更多调用,每个调用具有不同的参数,或者为A类型的对象简化一些构建器。

Something like this : 像这样的东西:

new A() { {
    func(2);
}
{
    func(3);
}
// ...
};

Is this possible to achieve ? 这有可能实现吗?

I think it is something you can find out the answer easily by actually writing some simple piece of code and try it out yourself. 我认为通过实际编写一些简单的代码并自己尝试,您可以轻松找到答案。

From my understanding (haven't tried) it is not possible. 根据我的理解(尚未尝试),这是不可能的。

I think you have to understand what is the meaning of: 我认为您必须了解以下内容的含义:

new A() { { func(2); } }

This is anonymous inner class which is just like writing something like 这是匿名内部类,就像编写类似

class A_anonymous extends A {
  { 
    func(2); 
  }
}

and do a 并做一个

new A_anonymous();

Further look into the class definition, it is in fact translated to 进一步研究类定义,实际上它被翻译成

class A_anonymous extends A {
  public A_anonymous() { 
    func(2); 
  }
}

So the answer is obvious. 因此答案很明显。 If func() is a private method in A, then of course you cannot use it such way. 如果func()是A中的私有方法,那么您当然不能以这种方式使用它。

The way to solve is simply make the visibility of the method to be protected (or higher). 解决方法是简单地使方法的可见性受到保护(或更高)。

Is it possible to access the private static method within the object creation scope? 是否可以在对象创建范围内访问私有静态方法?

Yes. 是。

Within constructor you can call a static method. 在构造函数中,您可以调用静态方法。

class AClass
{
    private void static aMethod1()
    {

    }

    private void static aMethod2()
    {

    }

    public AClass()
    {
        aMethod1();
        aMethod2();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM