提问人:Micah 提问时间:10/2/2017 最后编辑:Micah 更新时间:10/4/2017 访问量:124
导入两个同名的实用程序类。功能还是无用?
Importing two utility classes with same name. Feature or useless?
问:
对于两个名称相同的实用程序类,它们仅包含静态方法,我按如下方式进行:
- 只需导入第一个
- 创建了第二个类的实例。
例:
package util1;
public class Utility {
public static void method() {
System.out.println("First Utility. static method");
}
}
package util2;
public class Utility {
public static void method() {
System.out.println("Second Utility. static method");
}
}
import util1.Utility;
public class Component {
private static final util2.Utility anotherUtility = new util2.Utility();
public static void usedByReflection() {
Utility.method();
anotherUtility.method();
}
}
现在我不需要写一个完整的第二个util类名称来调用它的方法,但也许我没有预见到什么......?
附言: Component 类的方法由某个黑匣子通过反射调用。所有多线程安全功能都在 BlackBox 中。
更新:我找到了更好的技巧:
import util1.Utility;
public class Component {
private static final util2.Utility anotherUtility = null; // There are some changes
public static void usedByReflection() {
Utility.method();
anotherUtility.method();
}
}
现在我不创建新对象,但是否可以在没有任何错误的情况下使用它?
答:
2赞
mikeb
10/2/2017
#1
IMO,这很令人困惑,可以通过以下方式更清楚地处理:
public class CombinedUtilityComponent {
public static void usedByReflection() {
util1.Utility.method();
util2.Utility.method();
}
}
或者,更好的是,在代码中,您可以完全限定类名,它们将成为唯一的名称,而无需任何令人困惑的技巧。
评论
1赞
Oleg
10/2/2017
你说的“或者......完全限定类名“?这就是您在代码示例中所做的
0赞
Micah
10/2/2017
完整的类名可能类似于 com.somebeautifulfolder.someanotherbeautifulfolder。(...).last文件夹。BeautifulClass,然后不会明确使用全名。我把这个技巧用于普通视图代码,在编写它时,我会重构它。
0赞
mikeb
10/3/2017
@Oleg - 好吧,在我的示例中,我创建了一个类来组合这些方法。我使用“Or”作为连词来建议另一种选择:OP 可以“在您的代码中完全限定类名”,而不是我的示例(即新类),因此不需要新类。
1赞
John Kugelman
10/2/2017
#2
是的,这有效。不过,我不会这样做。
您正在调用一个方法,就好像它是实例方法一样。 对 的引用是无用的。static
anotherUtility.method()
anotherUtility
您还有一个不必要的实例化。如果禁用默认构造函数,则此技术将不起作用。util2.Utility
评论
0赞
Micah
10/4/2017
注意我的问题的更新。它无需构造函数即可工作)
评论
anotherUtility.method();
util2.Utility.method();