简体   繁体   English

如何在Java中对同一包的类使用静态导入

[英]How to use static import on classes of same package in Java

Within my project package "pypapo.alphabet" I would like to have one class "alphabetStatic" that contains all frequently used variables (paths, directories, files, constants, etc...) as static final fields throughout the project. 在我的项目包“ pypapo.alphabet”中,我希望有一个类“ alphabetStatic”,其中包含所有经常使用的变量(路径,目录,文件,常量等),作为整个项目中的静态最终字段。 In order to not fill up the code of the other classes with the "alphabetStatic"-prefix every time I access one of those static final fields I would like to perform some kind of "import static alphabetStatic". 为了不每次我访问那些静态最终字段之一时都用“ alphabetStatic”前缀填充其他类的代码,我想执行某种“导入静态alphabetStatic”。 I know that the import static statement refers to the classes of a package. 我知道import static语句引用包的类。 However is it possible to import the fields of a class in such manner? 但是,是否可以通过这种方式导入类的字段?

Nothing prevents you from importing package X from inside package X. 没有什么可以阻止您从包X 导入包X的。

So 所以

import static status pypapo.alphabet.alphabetStatic.*;

should definitely work for you. 应该肯定为您工作。

I know that the import static statement refers to the classes of a package. 我知道import static语句引用包的类。

Not really. 并不是的。 It refers to static members of a class. 它指的是类的static成员。
You can use import static with a fullquafiliedclassname.* (to mean any static member of the class) or with specific static field or method of a class. 您可以将import static与fullquafiliedclassname。*(表示类的任何静态成员)或类的特定static字段或方法一起使用。

For example to make an import static of a specific static field or method of a class, this is the syntax : 例如,使导入static特定静态字段或一类的方法,这是语法:

import static packages.Clazz.fieldOrMethod;

1) static field example 1)静态字段示例

So you could do it to import the static out field form System : 因此,您可以这样做以将静态out字段从System导入:

import static java.lang.System.out;

and use it : 并使用它:

out("...");

1) static method example : same syntax. 1)静态方法示例:语法相同。

import static org.junit.jupiter.api.Assertions.assertEquals*;

And use it : 并使用它:

assertEquals(expected, actual);

3) All static members of a class 3)所有静态成员

Just suffix it with a wildcard : 只需在后面加上通配符即可:

import static org.junit.jupiter.api.Assertions.*;

Try this: 尝试这个:

import static pypapo.alphabet.AlphabetStatic.*;

Note that classe names in Java must start with an uppercase letter. 请注意,Java中的类名称必须以大写字母开头。

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

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