简体   繁体   English

从另一个访问私有静态方法

[英]accesing private static method from another

I have main class with a private static method.我有一个带有私有静态方法的主类。 I want to access this method from another java class.我想从另一个 java 类访问这个方法。 I tried some ways,however they didnt work.我尝试了一些方法,但它们不起作用。 How can I access the method?如何访问该方法?

below main class like this;在这样的主类下面;

public class RandomGenerate {

    public static void main(String[] args) throws Exception {
        System.out.print.ln("main method");
    }

    private static synchronized void createRandom(PersonObj person, int number, List s) {
        System.out.println("deneme");
    }
}

And I want to call createRandom from another java class like this;我想从这样的另一个 java 类调用createRandom

public class Deneme {
    RandomGenerate rg = new RandomGenerate();
    RandomGenerate.createRandom(person, number, sList);
}

Then, netbeans shows method has private access.然后,netbeans 显示方法具有私有访问权限。

You shouldn't access a private function/variable from outside of that class.您不应该从该类之外访问private函数/变量。 If you need to access a private variable of a class, you can create an accompanying getter for that variable, and call the getter function on the class.如果您需要访问某个类的private变量,您可以为该变量创建一个伴随的getter ,并在该类上调用getter函数。

For functions, if the class you are trying to access the function from is in the same package, or is a subclass as the class with the function, change private to protected .对于函数,如果您尝试从中访问函数的类在同一个包中,或者是具有该函数的类的子类,请将private更改为protected protected allows members in the same package, or subclasses, to access the item, but nothing outside of the package. protected允许同一包或子类中的成员访问该项目,但不允许包外的任何成员访问。

A good read on visibility in Java is: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html关于Java可见性的一个很好的读物是: http : //docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

That shows a table:这显示了一个表:

                  Access Levels

Modifier    Class   Package Subclass    World

public      Y       Y       Y           Y

protected   Y       Y       Y           N

no modifier Y       Y       N           N

private     Y       N       N           N

Primarily主要是

If you need to use it outside the class, make it public (or protected if you need it only in subclasses, or the default [no keyword at all] if you need it just in the package).如果您需要在类之外使用它,请将其设为public (或者如果您只在子类中需要它,则将其设为protected ,或者如果您只在包中需要它,则使用默认 [无关键字])。 If you need to use it outside the class and it's private and you can't make it not private , that's a design problem you should fix.如果您需要在课堂外使用它并且它是private并且您不能使它不是private ,那么这是一个您应该解决的设计问题。

But...但...

...you can work around it using reflection ( tutorial , docs ), which allows you to get the method and call it even though it's private. ...您可以使用反射(教程文档)来解决它,它允许您获取方法并调用它,即使它是私有的。 Once you have the Method object, you have to call setAccessible to true before you call it.一旦有了Method对象,就必须在调用它之前将setAccessible调用为true

But again, that's a workaround.但同样,这是一种解决方法。 Use the correct access modifier.使用正确的访问修饰符。

private methods are not accessible from another class by definition.根据定义, private方法不能从另一个类访问。 If you need to call it you can create another public method that internally calls the private one or change the access modifier to public/protected/default.Example:如果您需要调用它,您可以创建另一个内部调用私有方法的公共方法或将访问修饰符更改为 public/protected/default。例如:

private static String secretMethod() { return "secret"; }
public static String knownMethod() { return secretMethod(); }

You will want to choose the proper access modifier for the method, the options are: public , protected , default (which is indicated by not providing a modifier), and private .您需要为该方法选择适当的访问修饰符,选项是: publicprotecteddefault (通过不提供修饰符表示)和private

A good explanation is here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html一个很好的解释在这里: http : //docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

As mentioned in the comments, you can use public to open it up, but if you don't want such a wide access, you could start with default (which allows you to access the method if you're in the same package), or protected (which is the same as default, but also allows child classes to access the method, if you wanted to extend the class).正如评论中提到的,您可以使用public来打开它,但是如果您不想要如此广泛的访问权限,您可以从default开始(如果您在同一个包中,它允许您访问该方法),或protected (这与默认值相同,但也允许子类访问该方法,如果您想扩展该类)。

As a general rule, stick with the most restrictive permission.作为一般规则,坚持使用最严格的许可。 It's easier to open up permissions later, but very hard to remove them.以后打开权限更容易,但很难删除它们。

Just change the visibility from private to public so other Instances can access them.只需将可见性从private更改为public以便其他实例可以访问它们。 Private means it is only for the own class available.私有意味着它仅适用于自己的可用类。

You can not access Private methods outside the class which defines this method.您不能访问定义此方法的类之外的私有方法。 You should make it Public to give full access to any classes or protected to give access to all the classes in the same package.您应该将其设为 Public 以提供对任何类的完全访问权限,或者设为 protected 以提供对同一包中所有类的访问权限。

Click [here] http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html For more reference.单击 [此处] http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html以获取更多参考。

If you really wish to access private method, you will have to use Java Reflection.如果您真的希望访问私有方法,则必须使用 Java 反射。 See this sample code.请参阅此示例代码。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Workspace {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ClassWithPrivateMethod cwpm = new ClassWithPrivateMethod();
        Method m = cwpm.getClass().getDeclaredMethod("privateMethod", String.class);
        m.setAccessible(true); //This is a key statement for accessing private methods
        m.invoke(cwpm, "test");
    }
}

class ClassWithPrivateMethod {
    private void privateMethod(String someParam){
        System.out.println("I am private!!!");
        System.out.println("Parameter: " + someParam);
    }
}

This code will print following output:此代码将打印以下输出:

I am private!!!
Parameter: test

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

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