简体   繁体   English

禁止 Java 中不推荐使用的导入警告

[英]Suppress deprecated import warning in Java

In Java, if you import a deprecated class:在 Java 中,如果您导入已弃用的类:

import SomeDeprecatedClass;

You get this warning: The type SomeDeprecatedClass is deprecated您收到此警告: The type SomeDeprecatedClass is deprecated

Is there a way to suppress this warning?有没有办法抑制这个警告?

To avoid the warning: do not import the class为了避免该警告:导入类

instead use the fully qualified class name而是使用完全限定的类名

and use it in as few locations as possible.并在尽可能少的地方使用它。

在您的类或方法上使用此注释:

@SuppressWarnings( "deprecation" )

As a hack you can not do the import and use the fully qualified name inside the code.作为一个黑客,你不能在代码中进行导入和使用完全限定的名称。

You might also try javac -Xlint:-deprecation not sure if that would address it.您也可以尝试 javac -Xlint:-deprecation 不确定是否可以解决它。

I solved this by changing the import to:我通过将导入更改为:

import package.*

then annotating the method that used the deprecated classes with @SuppressWarnings("deprecation")然后使用@SuppressWarnings("deprecation")注释使用已弃用类的方法

Suppose that you are overriding/implementing an interface with a deprecated method (such as the getUnicodeStream(String columnLabel) in java.sql.ResultSet ) then you will not get rid of deprecation warnings just by using the annotation @SuppressWarnings( "deprecation" ) , unless you also annotate the same new method with the @Deprecated annotation.假设您使用已弃用的方法(例如java.sql.ResultSetgetUnicodeStream(String columnLabel)覆盖/实现了一个接口),那么仅通过使用注释@SuppressWarnings( "deprecation" )将无法摆脱弃用警告, 除非您还使用@Deprecated注释来注释相同的新方法。 This is logical, because otherwise you could undeprecate a method by just overriding its interface description.这是合乎逻辑的,否则您可以通过覆盖其接口描述来取消弃用方法。

you can use:您可以使用:

javac FileName.java -Xlint:-deprecation javac FileName.java -Xlint:-deprecation

But then this will give you warnings and also tell you the part of the code that is causing deprecation or using deprecated API.但是这会给你警告,并告诉你导致弃用或使用弃用 API 的代码部分。 Now either you can run your code with these warnings or make appropriate changes in the code.现在,您可以运行带有这些警告的代码,也可以对代码进行适当的更改。

In my case I was using someListItem.addItem("red color") whereas the compiler wanted me to use someListItem.add("red color");就我而言,我使用的是someListItem.addItem("red color")而编译器希望我使用someListItem.add("red color"); . .

If @SuppressWarnings("deprecation") is not working for you like for me.如果@SuppressWarnings("deprecation")不像我那样适合你。 You can find exact squid number in sonar lint plugin.您可以在声纳 lint 插件中找到确切的鱿鱼编号。 And then you can simply suppress warning: @SuppressWarnings("squid:CallToDeprecatedMethod")然后你可以简单地抑制警告: @SuppressWarnings("squid:CallToDeprecatedMethod")

在此处输入图片说明

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

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