我可以告诉 javac 忽略 `import foo.Bar` 的缺失吗? [英] Can I tell javac to ignore the lack of `import foo.Bar`?

查看:21
本文介绍了我可以告诉 javac 忽略 `import foo.Bar` 的缺失吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用反射在运行时加载 MyClass.class(一个外部文件).

MyClass.class 使用库 Bar,这意味着我需要将 import foo.Bar; 放在文件.

但是,Bar 库已经加载到加载 MyClass 的主类中.

有没有办法让我告诉 javac 忽略 Bar 不存在而直接编译没有它?

解决方案

不,这是不可能的.在编译一个类时,编译器没有记忆"哪些类已经加载"了(不要将这与与类加载相关的概念混淆——这是一个完全不同的故事).每当编译一个类并且发现对不在同一个包中的类的引用时,都需要使用 import 语句.

话虽如此,您的问题似乎存在矛盾:根据您所说的,MyClass 已经编译,因为文件 MyClass.class 存在,所以有这里没有涉及编译器.执行加载的是类加载器.在这种情况下,就类加载器而言,如果 Bar 已经在主类中被引用,那么它就不会从 MyClass 中再次加载.>

I'm using reflection to load MyClass.class (an external file) at runtime.

MyClass.class uses the library Bar, which would mean that I need to place import foo.Bar; at the top of the file.

However, the Bar library is already loaded in the main class loading MyClass.

Is there a way for me to tell javac to ignore that Bar doesn't exist and just compile without it?

解决方案

No this is not possible. When compiling a class, the compiler has no "memory" of which classes were already "loaded" (don't confuse this with the concept related to classloading -- that's a completely different story). Whenever a class is compiled and a reference to a class is found that is not in the same package, an import statement is required.

This being said, it seems there is a contradiction in your question: from what you say, MyClass is already compiled because the file MyClass.class exists, so there is no compiler being involved here. It's the classloader that does the loading. In this case, as far as the classloader is concerned, if Bar was already referenced in the main class, then it won't be loaded again from within MyClass.

这篇关于我可以告诉 javac 忽略 `import foo.Bar` 的缺失吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆