我创建了两个自定义java DTO类
我尝试初始化它们但得到错误
...
PeriodicDataToServer pData = new PeriodicDataToServer(){
location = new Location() {
longtitude ="", latitude = "";
};
}
...
public class PeriodicDataToServer {
public Location location;
}
public class Location {
public String longtitude;
public String latitude;
}
...
错误:
Syntax error on token "location", VariableDeclaratorId expected after this token
Syntax error on token "longtitude", } expected
答案 0 :(得分:3)
你可能意味着:
PeriodicDataToServer pData = new PeriodicDataToServer() {{
location = new Location() {{
longtitude ="", latitude = "";
}};
}};
这也是我喜欢的技巧,但它有一个很大的缺点:它会创建匿名类。
对于其他读者:
class A { int n; }
A a = new A() {{ n = 3; }};
有一个内部初始化块{ n = 3; }
,如:
class B {
int[] a = new int[2};
{
a[0] = 12;
a[1] = 34;
}
}
答案 1 :(得分:1)
PeriodicDataToServer pData = new PeriodicDataToServer(){
location = new Location() { // this is not possible.
longtitude ="", latitude = "";
};
}; // <- this semicolon was missing
您在这里使用匿名课程。你正在尝试用javascript表示法初始化字段!
但您可以使用初始化块(这是一种非常糟糕的样式):
PeriodicDataToServer pData = new PeriodicDataToServer() {
{ // this is the init block for PeriodicDataToServer
Location location = new Location() {
{ // this is the init block for Location
longtitude ="", latitude = "";
}
};
}
};