如何从 Scala 访问名为 "type" 的 Java 对象的字段
How to access a Java object's field named "type" from Scala
我已经有一个用 Java 编写的 class(可以说这个 class 叫做 X
),它包含一个名为 [=15= 的字段/成员].
我现在想编写一个 Scala class / 对象来创建一个 X
类型的对象并访问该对象的 type
成员。
然而,由于 type
是 Scala 中的关键字,所以这不起作用。 Eclipse 中的错误信息是:identifier expected but 'type' found.
问题:是否可以在不重命名的情况下访问该字段?
一个工作示例:
Java Class:
public class X {
public final int type = 0;
}
Scala 应用程序:
object Playground extends App {
val x : X = new X();
System.out.println(x.type); // This does not work!
}
您可以使用反引号将保留字用作名称,例如type
。有关更多信息,请参阅以前的问题:
Is there a way to use "type" word as a variable name in Scala?
要么使用反引号,要么定义一个 gettter。
object Playground extends App {
val x : X = new X();
System.out.println(x.`type`)
}
或使用 getter、
public class X {
public int type = 0;
public int getType() {
return type;
}
}
object Playground extends App {
val x : X = new X();
System.out.println(x.getType());
}
我已经有一个用 Java 编写的 class(可以说这个 class 叫做 X
),它包含一个名为 [=15= 的字段/成员].
我现在想编写一个 Scala class / 对象来创建一个 X
类型的对象并访问该对象的 type
成员。
然而,由于 type
是 Scala 中的关键字,所以这不起作用。 Eclipse 中的错误信息是:identifier expected but 'type' found.
问题:是否可以在不重命名的情况下访问该字段?
一个工作示例:
Java Class:
public class X {
public final int type = 0;
}
Scala 应用程序:
object Playground extends App {
val x : X = new X();
System.out.println(x.type); // This does not work!
}
您可以使用反引号将保留字用作名称,例如type
。有关更多信息,请参阅以前的问题:
Is there a way to use "type" word as a variable name in Scala?
要么使用反引号,要么定义一个 gettter。
object Playground extends App {
val x : X = new X();
System.out.println(x.`type`)
}
或使用 getter、
public class X {
public int type = 0;
public int getType() {
return type;
}
}
object Playground extends App {
val x : X = new X();
System.out.println(x.getType());
}