简体   繁体   中英

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

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"
   }
}

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 (eg 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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