我在使用 Eclipse 时经常遇到问题。考虑以下示例:
如您所见,我按下了 Ctrl+Shift+O。我可以从弃用 和未弃用 注释中进行选择。我的问题是我经常收到几十个类,其中一半已被弃用(一个完美的例子是 JUnit Assert
类)。
我的问题是如何让 Eclipse 在组织导入时忽略所有 已弃用的类?
最佳答案
目前 Eclipse 不提供这样的选项... Eclipse Documentation for Organise Imports (Kepler version) .
然而,用软糖你可以达到同样的结果......
Eclipse 允许您提供要过滤掉的类/包列表。 为此,请导航至首选项 > 类型过滤器。
我已在我的环境中完成此操作,以确保在我真正需要“java.util.List”时不会提示“java.awt.List”。
您想要的是将所有已弃用的类添加到此列表中。
此列表在您的 Eclipse 工作区首选项中维护...
File ... C:\Users\[YOUR_USER_NAME]\workspace\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.jdt.ui.prefs
Property ... org.eclipse.jdt.ui.typefilter.enabled=java.awt.List;
所需要做的就是创建一个已弃用类的列表,并将其存储在此属性文件中。
Eclispe 可以帮助创建这个列表... 对“已弃用”执行“Java 搜索”。
然后按类型对结果进行分组。
并使用“Copy Qualified Name”复制结果
结果将包含泛型,这应该被删除。
例如,“javafx.scene.control.Cell
除了包含已弃用的类之外,结果还将包含任何具有“已弃用”一词的类。这可以是注释或方法注释。需要过滤此列表以仅保留已弃用的类。
下面的脚本处理此类列表以删除泛型,并过滤掉未弃用的类(即,只有方法弃用)。类列表是从名为“DeprecatedClassList.txt”的文件中读取的。当它无法检查类注释时,它会跳过该类并将其打印出来(用于手动检查)。
import java.lang.annotation.Annotation;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ConfigurationGenerator {
public static void main(String[] args) throws Exception {
List<String> cleanedList = Files
.readAllLines(Paths.get("DeprecatedClassList.txt")).stream()
.map(ConfigurationGenerator::removeGenerics)
.filter(ConfigurationGenerator::hasDeprecatedConstructor)
.collect(Collectors.toList());
String propertyName = "org.eclipse.jdt.ui.typefilter.enabled=";
String propertyValue = String.join(";", cleanedList).concat(";");
String configuration = propertyName + propertyValue;
System.out.println("Configuration property...");
System.out.println(configuration);
}
public static String removeGenerics(String className) {
int openingBracket = className.indexOf("<");
if (openingBracket == -1)
return className;
else
return className.substring(0, openingBracket);
}
public static boolean hasDeprecatedConstructor(String className) {
Class theClass = null;
try {
theClass = Class.forName(className);
} catch (Throwable e) {
// Ignore bad results
System.out.println("Skipping: " + className);
return false;
}
Annotation[] annotations = theClass.getAnnotations();
Optional<Annotation> deprecatedConstructor = Stream
.of(annotations)
.filter(annotation -> annotation.toString().equals(
"@java.lang.Deprecated()")).findAny();
return deprecatedConstructor.isPresent();
}
}
不过,这种方法存在一个问题。当不推荐使用的版本不存在时,您可能希望使用已弃用的类。如果有意隐藏已弃用的类,您将看不到它。要解决此问题,请确保将它们从过滤器中排除。
关于java - 如何防止 Eclipse 在导入时提供已弃用的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22937127/