简体   繁体   English

在Scala / Java中使用`getClass`方法?

[英]The usage of `getClass` method in Scala/Java?

I find this works well (Scala codes) 我发现这很好用(Scala代码)

class myClass(i:Int) {

}

val a = new myClass(1)

But this doesn't work: 但这不起作用:

val b = a.getClass
val c = new b(1)

The compiler will say cannot resolve "b". 编译器会说无法解析“b”。

Does anyone have ideas about this? 有没有人有这个想法? What are the difference between b and myClass here? bmyClass有什么区别? Does this mean myClass is not an object, while b is an object? 这是否意味着myClass不是一个对象,而b是一个对象?

myClass is a type . myClass是一种类型 b is a value (or term ) of type java.lang.Class . bjava.lang.Class类型的 (或术语 )。 new requires the former kind. new要求前者。

new expects a class name in the source code. new期望源代码中有一个类名。 The compiler will not try to read b as an expression that somehow resolves to a class name. 编译器不会尝试将b读取为以某种方式解析为类名的表达式。

What you seem to be trying to do is reflection: Using an object to describe the class (your b ) at runtime and getting an instance from that. 你似乎要做的就是反思:使用一个对象在运行时描述类(你的b )并从中获取一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM