Using a private method from another class in Java

I have two classes:

public class Class1{} public class Class2{ private void simpleMethod(){ /*...*/ } } 

In Class2 , I have a private method simpleMethod() , and I want to use it in Class1 in the same project. I do not want to rename this method as public because I do not want to show it in my API. Can I create a public method without showing it in the API? Or something else?

+6
source share
5 answers

If Class1 and Class2 are in the same package, you can simply remove the private modifier by making the package-private method. This way, it will not appear in the API, and you can access it from Class1 .

Before:

 public class Class2 { // method is private private void simpleMethod() { ... } } 

After:

 public class Class2 { // method is package-private: can be accessed by other classes in the same package void simpleMethod() { ... } } 
+13
source

If both classes are in the same package, you can leave simpleMethod visible by default, so it can only be used by a class and classes in a single package.

 package org.foo; public class Class1 { //visibility for classes in the same package void simpleMethod() { } } package org.foo; public class Class2 { public void anotherMethod() { Class1 class1 = new Class(); class1.simpleMethod(); //compiles and works } } package org.bar; import org.foo.Class1; public class Class3 { public void yetAnotherMethod() { Class1 class1 = new Class1(); class1.simpleMethod(); //compiler error thrown } } 
+8
source

Well, another way is to have two different interfaces. One for your public API and one for your internal API, your Class2 object will implement both. Everyone who deals with the API will talk to him through the open interface that you opened

 public class Class2 implements PublicApi2 { public void somePrivateMethod() { ... } @Override public void somePublicMethod() { ... } } 

(two interfaces were not implemented here, since there is really no need for a "closed" one, since the objects in your library / framework / everything can deal with specific classes, but this is up to you)

Clients will always refer to your object as a type of "PublicApi2" and will never deal with a specific implementation (Class2), while your internal clans will.

+3
source

Use either protected or omit the access modifier completely.

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

+1
source

In addition to the above scenario, you can use the reflection API to access the private method, as shown below:

 Class a = Class.forName(""); Method method = a.getDeclaredMethods()[0];//retrieve your method here method.setAccessible(true); 
+1
source

Source: https://habr.com/ru/post/985214/


All Articles