简体   繁体   English

是否可以在同一包中有两个具有相同名称的类?

[英]Is it possible to have 2 classes with the same name and in the same package?

I'm developing a grails app, and I need to modify a groovy class that is in a plugin, so I decided to override the class, so I have these method and class in my plugin: 我正在开发grails应用程序,并且需要修改插件中的groovy类,因此我决定覆盖该类,因此我的插件中包含以下方法和类:

def example = new a();
a.method();

class a {
   void method() {
      println "2";
   }
}

all this was Inside the plugin, so I want to create another class in the same package in my project, to change the method, but how can I set my new class to run instead the plugin's? 所有这些都在插件内部,所以我想在项目的同一包中创建另一个类,以更改方法,但是如何设置新类来代替插件运行呢? or is it impossible? 还是不可能?

class a {
   void method() {
      println "4";
   }
}

Yes you can. 是的你可以。 It is called class shadowing. 这称为类阴影。 But I would advice against it most of the times. 但是我大多数时候都会反对。 You only need to let the jvm load your class before the plugin class. 您只需要让jvm在插件类之前加载您的类。

是的,您只需要确保您的类在插件版本之前位于类路径中即可。

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

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