简体   繁体   English

有没有办法将包私有类传递给静态方法

[英]Is there a way to pass a package private class to static method

I'm wondering if there is a way to call static method from another package which take a package private class as a parameter? 我想知道是否有一种方法可以从另一个将包私有类作为参数的包中调用静态方法? is that the only way to move MessagePackagePrivate class to another .java file and make it public ? 这是将MessagePackagePrivate类移动到另一个.java文件并使其公开的唯一方法吗? it gives this error if i don't do that : "The type MessagePackagePrivate is not visible" which is normal. 如果我不这样做,它将给出此错误:“ MessagePackagePrivate类型不可见”是正常的。

So if it is the case that means, even if your class expose a static method to be used publicly ,that class cannot be used if it is not being called in the same package? 因此,如果是这样的话,即使您的类公开了要公开使用的静态方法,那么如果未在同一包中调用该类,该类也将无法使用?

here is the code snippet: 这是代码片段:

MainClass.java MainClass.java

package packageA;

import packageB.*;

public class MainClass {
    public static void main(String[] args) {
        ClassB.printString(new MessagePackagePrivate("Package problem"), 12);
    }
}

ClassB.java ClassB.java

package packageB;

public class ClassB {

    public static void printString( MessagePackagePrivate message , int numbers) {
        System.out.println(message.getMessage() + " numbers: " + numbers );
        // other logics will be implemented here ...
    }
}

    class MessagePackagePrivate {
        private String text;

        MessagePackagePrivate(String text) {
            this.text = text;
        }

        public String getMessage() {
            return this.text;
        }
    }

This is what interfaces are for. 这就是接口的作用。

You have a public interface (well, all interfaces are public) that defines all the methods that need to be publicly accessible and a package private implementation. 您有一个公共接口(嗯,所有接口都是公共的),该接口定义了需要可公开访问的所有方法以及一个包私有实现。 And the method you pass the object to only needs to know about the interface. 您将对象传递给的方法只需要了解接口。

In your case you'll have something like this: 在您的情况下,您将获得以下内容:

public interface Message {
  public String getMessage();
}

And then 接着

class MessagePackagePrivate implements Message {
   ...
}

Finally: 最后:

public static void printString( Message message , int numbers) {
   ...
}

您可以实现一个接口(例如Printable ),并将该接口用作静态方法中的参数类型。

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

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