在其他类中获取变量
我需要在其他类中获取变量inString
。 我怎样才能做到这一点?
public class main { public static StringBuffer inString; public static void main(String[] args) { inString = new StringBuffer("Our aim is to make a 15 realistic game, where grinding powerlines and doing a tailwhip isn't easy, like in the real world. A game in which you will feel like you're actual riding. A game in which creativity and beauty are combined. "); inString = new StringBuffer(inString.toString().replaceAll(" +", " ")); } }
所以我尝试使用System.out.println(main.inString);
在我的Textcl.class中,但是得到null
。
你将得到null,因为inString永远不会被评论中的Robert Kilar正确指出。
您可以使用类名来引用静态变量。
示例ClassName.variablename。 在你的情况下
main.inString
运行你的主类。 当你运行inString时,在类的构造函数中初始化。 现在您可以在Myclass中引用相同的内容,如下所示。
public class main { public static StringBuffer inString; public main() { inString = new StringBuffer("Our aim is to make a 15 realistic game, where grinding powerlines and doing a tailwhip isn't easy, like in the real world. A game in which you will feel like you're actual riding. A game in which creativity and beauty are combined. "); inString = new StringBuffer(inString.toString().replaceAll(" +", " ")); new MyClass(); } public static void main(String[] args) { new main(); } }
现在在MyClass中引用静态变量。
class MyClass { public MyClass() { System.out.println("............."+main.inString);// refer to static variable } }
您还可以将变量传递给类的构造函数。
public class main { public StringBuffer inString; public main() { inString = new StringBuffer("Our aim is to make a 15 realistic game, where grinding powerlines and doing a tailwhip isn't easy, like in the real world. A game in which you will feel like you're actual riding. A game in which creativity and beauty are combined. "); inString = new StringBuffer(inString.toString().replaceAll(" +", " ")); new MyClass(inString); } public static void main(String[] args) { new main(); } }
然后在Myclass
public class MyClass { public MyClass(StringBuffer value) { System.out.println("............."+value); } }
请检查链接@ 为什么静态变量被认为是邪恶的?
您可以通过以下方式访问它: main.inString
其中main
是声明public static
变量的类的名称。
由于您在类中创建了静态字段,因此您可以使用类名来访问它,即
main.inString
使用JavaBeans并将其作为其中一个字段存储在其中,并使用getter和setter。
JavaBeans是具有属性的Java类。 将属性视为私有实例变量。 由于它们是私有的,因此可以通过类中的方法从类外部访问它们。 更改属性值的方法称为setter方法,检索属性值的方法称为getter方法。
public class VariableStorage implements Serializable { private String inString; public String getInString() { return inString; } public void setInString(String inString) { this.inString = inString; } }
使用以下命令在mail方法中设置变量:
VariableStorage variableStorage = new VariableStorage(); variableStorage.setInString(inString);
然后使用对象序列化来序列化此对象,并在其他类中反序列化此对象。
在序列化中,对象可以表示为包含对象数据的字节序列,以及有关对象类型和对象中存储的数据类型的信息。
将序列化对象写入文件后,可以从文件中读取并反序列化。 也就是说,表示对象及其数据的类型信息和字节可用于在内存中重新创建对象。
如果您需要相关教程,请参阅Java中的序列化 。