Java – why doesn’t the compilation of public API leaked internal types fail?

I have the following Java 9 modules:

module com.example.a {
    exports com.example.a;
}

Use export type:

public class Api {

    public static void foo(ImplDetail args) {}
}

And a non export type:

package com.example.b.internal;

public class ImplDetail {}

Exported types use non - exported types as method parameter types in public methods I assume that the compiler will reject this inconsistent class configuration because clients in other modules cannot actually call the foo () method because they cannot instantiate parameter types

To my surprise, this module was successfully compiled by javac I can see the special case of passing null. I will still consider such API definition format error, and think that it should not be supported and ideally executed by the compiler

What are the reasons for not prohibiting this situation?

Solution

Of course, using non exported types in the API is a bad style and is likely to be a design error, but I'm quite clear that javac can't make it a compile time error

Note that it is always possible to use private types in public APIs, returning to Java 1.0

You have noticed that code outside the module can still call API foo(null).

In other cases, callers can still use APIs with non empty references Consider a class public class sub in package com example. Extend impldetail in a This class sub is public and exported, so it can be encoded outside the module Therefore, external code can call API with an instance of sub obtained from somewhere foo(sub).

But to be sure, javac can tell whether there are subclasses of impldetail in any exported package. If not, will a compile time error be issued? unnecessary. Due to the possibility of separate compilation, new classes may be introduced into the module after the compilation step including API Alternatively, to do this, you can recompile module info Class file to change the collection of exported packages

For these reasons, I think it is inappropriate for javac to cause errors when compiling API classes However, javac does have an option - xlint: exports, which flags this as a warning

During the construction process, such as jmod tool or some post module audit tools, you can also mark the non export types used in the exported API However, I don't think there is anything at present

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>