[英]Initializing an object in a method in Java
Suppose I want to have a bunch of private static objects in a class, but they are complicated objects and I would like to use a specific function to initialize them with some parameters. 假设我想在一个类中有一堆私有静态对象,但是它们是复杂的对象,并且我想使用特定的函数通过一些参数来初始化它们。 Ideally, I would write code like this:
理想情况下,我将编写如下代码:
public class TestClass{
private Class ComplicatedObject{
private int anInteger;
private String aString;
public ComplicatedObject(int inputInt,String inputString){
anInteger = inputInt;
aString = inputString;
}
public void someMethod(){
//do a thing
}
}
private void MakeAThing(ComplicatedObject theThing, int someInt,int someString){
theThing = new ComplicatedObject(someInt,someString);
//do extra stuff that one might want to do here
}
private static ComplicatedObject IMPORTANT_OBJECT;
public TestClass(){
MakeAThing(IMPORTANT_OBJECT, 0,"Test");
IMPORTANT_OBJECT.someMethod();
}
}
This will crash because (as far as I understand Java) when I call someMethod()
on IMPORTANT_OBJECT
, IMPORTANT_OBJECT
is actually null - the MakeAThing
method did create a new object, but only its internal reference ( theThing
) actually referenced the new object. 这会崩溃,因为(就我所了解的Java而言),当我在
IMPORTANT_OBJECT
上调用someMethod()
时, IMPORTANT_OBJECT
实际上为空MakeAThing
方法确实创建了一个新对象,但只有其内部引用( theThing
)实际引用了该新对象。 The reference for IMPORTANT_OBJECT
is still null. IMPORTANT_OBJECT
的引用仍然为空。
Is there any way I can write a method that will change the reference for IMPORTANT_OBJECT
to reference a new object? 有什么办法可以编写一种方法来更改
IMPORTANT_OBJECT
的引用以引用新对象?
(yes, I know that one easy solution would be to just say IMPORTANT_OBJECT = new Object();
and then add the parameters later, but this will make my code really messy (there are many "important objects") and if there is another way I'd much prefer it.) (是的,我知道一个简单的解决方案是只说
IMPORTANT_OBJECT = new Object();
然后在以后添加参数,但这会使我的代码非常混乱(有许多“重要对象”),如果还有其他我更喜欢的方式。)
How about function that return new ComplicatedObject: 返回新的ComplicatedObject的函数怎么样:
private ComplicatedObject MakeAThing(int someInt,int someString){
return new ComplicatedObject(someInt,someString);
}
And just initialize the IMPORTANT_OBJECT in TestClass constructor 并在TestClass构造函数中初始化IMPORTANT_OBJECT
public TestClass(){
IMPORTANT_OBJECT = (0,"Test");
IMPORTANT_OBJECT.someMethod();
}
Or have I misunderstood the question? 还是我误解了这个问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.