How to Access package private Class from a Class in some other package?

后端 未结 10 1274
情歌与酒
情歌与酒 2020-12-13 21:57

I have following classses

Hello.java

package speak.hello;

import java.util.Map;

import speak.hi.CustomMap;
import speak.hi.Hi;

public cla         


        
相关标签:
10条回答
  • 2020-12-13 22:36

    It may not be possible because:

    Class :

    Accessible to class from same package?

    • public : yes
    • protected : yes
    • default : yes
    • private : no

    Accessible to class from different package?

    • public : yes
    • protected : no
    • default : unless it is a subclass
    • private : no
    0 讨论(0)
  • 2020-12-13 22:37

    1st class is in package a.b.c.class1 but class1 is private as well as abstract 2nd class is in package a.b.c.class2 extends class1 but class2 is public

    3rd class is in package x.y.z.class3

    So as to access class1 in class 3 you can write something like:-

    Class baseClass = (new class2()).getClass(); and use the instance of its superclass then use:- baseClass.getSuperClass(); and use it wherever you want.

    But then again the baseclass was made abstract and private for a reason hence not advisable to do so but then again this solution could be used as a workaround.

    0 讨论(0)
  • 2020-12-13 22:38

    I would think that if the authors of a library did not make a particular class part of the public API, it is because they don't want other people using it. You should respect the decision even though you can break it using reflection. Using private API is simply bad programming.

    0 讨论(0)
  • 2020-12-13 22:47

    Adding this solution for sake of completeness.

    One option that I know is to move speak.hello.Hello to speak.hi.Hello as Now Hello is in package speak.hi it can access package private Class Hi

    package speak.hi;
    
    public class Hello {
    
        private Hi hi;
    
        Hello(Hi hi) {
            this.hi = hi;
        }
    
        public String sayHello() {
            return "Hello";
        }
    
        public String sayHi() {
            return hi.sayHi();
        }
    
        public static void main(String[] args) {
            Hello hello = new Hello(new Hi());
            System.out.println(hello.sayHello());
            System.out.println(hello.sayHi());
        }
    
    }
    
    0 讨论(0)
  • 2020-12-13 22:48

    Not possible. The security model is this : a model to provide security :) If you designed class Hi and delivered it to customers with private access, you wouldn't like them to be able to bypass your restrictions, would you?

    0 讨论(0)
  • 2020-12-13 22:48

    Not Possible you can not create your Hi class as private.

    0 讨论(0)
提交回复
热议问题