简体   繁体   English

如何抑制Java类实例上的静态方法?

[英]How to suppress static methods on class instance on Java?

For example, IntelliJ doesn't show the static sleep method on an instance variable 例如,IntelliJ在实例变量上未显示静态睡眠方法

Thread z = new Thread();
z.sleep(1000); // Eclipse shows sleep as part of z, while IntelliJ do not

It would appear that sleep is part of z variable 看来睡眠是z变量的一部分

How to prevent Eclipse from showing static methods on instance variable? 如何防止Eclipse在实例变量上显示静态方法? And how to make that a compilation error if at all possible, Eclipse-wise and in command-line? 以及如何尽可能地在Eclipse和命令行中使该编译错误?

Not sure you can remove it from options, but you can make Eclipse yield error for that: 不确定是否可以将其从选项中删除,但是您可以为此使Eclipse yield错误:

Preferences -> Java -> Compiler -> Errors/warnings -> Non-static access to static member -> set as Error. 首选项-> Java->编译器->错误/警告->对静态成员的非静态访问->设置为错误。

在此处输入图片说明

This is maybe more of a workaround but in the Save Actions ( Preferences->Java->Editor->Save Actions ) you can ask to “ Change non static accesses to static members using declaring type ” which will automatically remove such usage. 这也许是一种解决方法,但是在“ 保存操作”“首选项”->“ Java”->“编辑器”->“保存操作” )中,您可以要求“ 使用声明类型更改对静态成员的非静态访问 ”,这将自动删除此类用法。

Also, Eclipse does not normally suggest static proposals first. 另外,Eclipse通常不会首先建议静态建议。 If it is the case, you should check your Content Assist settings ( Preferences->Java->Editor->Content Assist ). 如果是这种情况,则应检查Content Assist设置( Preferences-> Java-> Editor-> Content Assist )。 Especially, ensure that Sort proposals is set to “ by relevance ”. 特别是,请确保将“ 排序建议 ”设置为“ 按相关性 ”。

You can't make it a compilation error from command line, because object has its class, and on this object you CAN invoke static method, which would affect not only this object. 您不能通过命令行将其设为编译错误,因为对象具有其类,并且您可以在该对象上调用静态方法,这不仅会影响该对象。 Because of this globally influence it's just a better design to invoke static method from class then from object, that's why IntelliJ prevents you from this. 由于这种全局影响,从类中调用静态方法然后从对象中调用静态方法是一个更好的设计,这就是IntelliJ阻止您这样做的原因。

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

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