-1

How can I access non public fields of non public class in other package?

I have below non public class and I want to call getString from a class in other package. How do I do that?

class ABC{
   String getString(){
     return "ABC"
   }
}
Neha
  • 1
  • https://www.concretepage.com/java/how-to-access-all-private-fields-methods-and-constructors-using-java-reflection-with-example – Steve Smith Jan 30 '19 at 17:12
  • 3
    You don't. There must be a reason why a field or an attribute is privae. However if you really want, take a look at Java Reflection: https://stackoverflow.com/questions/2407071/how-to-invoke-a-method-in-java-using-reflection – curiouscupcake Jan 30 '19 at 17:13
  • Possibly related: [How to call a private method from outside a java class](https://stackoverflow.com/q/11282265) – Pshemo Jan 30 '19 at 17:15

1 Answers1

0

This is what we call access-level in Java.

The documentation is actually pretty great and you can find it here. See the table below (Copied from documentation).

  • modifier -> It refers to public, private, <no modiefier> and protected.
  • scope -> It refers to where you are trying to access a field from (e.g. class, subclass, etc..)
  • Y -> Indicates that a field can be accessed from specific scope.
  • N -> Indicates that a field can not be accessed from specific scope.

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   |
+--------------------------------------------------+

It's actually a pretty interesting fact, that by adding no modifier your code is actually more secure (isolated from the 'world') than with the protected modifier.

To make a class (or a method) hidden from the rest of the world, apart from its own package, you give it no modifier. Like I showcase below with class ABC.

One possible solution, is to create another class, in that same package that can access only the fields you want the rest of the world to see.

package myPackage;

class ABC{
//implementation
}

package myPackage;

public class XYZ{

    /**
    *@return This method will invoke the getString() method in class ABC
    */
    public String getString(){
        return ABC.getString();//supposing that getString() is static
    }
}

package different_package;

import myPackage.*;

public class Main{

    //You could also do: 'myPackage.XYZ <variable name>'
    XYZ xyzInstance= new XYZ();

    /*some code*/

    // Accesses the method you want
    xyzInstance.getString();
}
Soutzikevich
  • 991
  • 3
  • 13
  • 29