如何在java中创建类中对象的快捷方式
我想知道有没有一种方法可以在java的另一个类中创建一个对象的快捷方式,比如说我有一个字符串,我想在java的另一个类中访问它,而不需要先说类名,然后说字符串名如何在java中创建类中对象的快捷方式,java,Java,我想知道有没有一种方法可以在java的另一个类中创建一个对象的快捷方式,比如说我有一个字符串,我想在java的另一个类中访问它,而不需要先说类名,然后说字符串名 //Like this //This is the first class String Hello = "Testing"; //Here is the second class System.out.println(FirstClass.Hello); 我不想输入头等舱。您好,我只想输入您好
//Like this
//This is the first class
String Hello = "Testing";
//Here is the second class
System.out.println(FirstClass.Hello);
我不想输入头等舱。您好,我只想输入您好,我怎样才能做出这样的快捷方式(如果有办法的话)。根据具体情况,有两种解决方案 静态导入。 如果要访问的成员是静态的,则可以静态导入它。例如,如果您只想使用
out
访问System.out
,可以执行以下操作:
import static java.lang.System.out;
将该值赋给局部变量
如果不需要为要访问的成员分配新值,可以将该成员分配给局部变量
int myValue = Some.value.you.want.to.access;
现在,不用编写
Some.value.you.want.to.access
,只需编写myValue
就可以了,我假设您希望访问类中的对象,而不在该类中创建对象
您可以通过对对象所在的类/接口执行静态导入来实现这一点。请参考以下示例:
与要创建快捷方式的对象的接口:
public interface Constants {
Object OBJ = new Object();
String STR = "XYZ";
}
import static Constants.*;
public class UserClass {
public static void main(String... args){
System.out.println(OBJ.getClass());
System.out.println(STR);
}
}
执行上述界面的静态导入以使用对象快捷方式:
public interface Constants {
Object OBJ = new Object();
String STR = "XYZ";
}
import static Constants.*;
public class UserClass {
public static void main(String... args){
System.out.println(OBJ.getClass());
System.out.println(STR);
}
}
希望这有帮助。什么?请展示一些您试图访问/实现的代码。我已经更改了帖子。这是怎么回事?如果它在第一类中是一个静态字段,那么您可以在第二类中为它添加一个静态导入。如果不是,请尝试编程drunk@ComputerCoderAN如果你认为我的答案回答了你的问题,请考虑通过点击这个标记接受它!另外,记住不要过度使用静态导入。它们可能会导致名称冲突并降低可读性。