[英]Determine Scala-object's class in Java
I want to check if the given object
(which may be created in Scala
) is instance-of
a specific Class (which is a class
or an abstract class
in Scala
) in Java
: 我想检查给定object
(可能在Scala
创建)是否是Java
特定类(在Scala
为class
或abstract class
)的instance-of
:
public boolean accept(Object object) {
System.out.println("1: " + object);
System.out.println("2: " + object.getClass());
System.out.println("3: " + (object.getClass().getName() + " - " + RepointableActorRef.class.getName()));
System.out.println("4: " + (object.getClass() == RepointableActorRef.class));
System.out.println("5: " + (object instanceof RepointableActorRef));
System.out.println("6: " + (object instanceof ActorRef));
System.out.println("7: " + ActorRef.class.isAssignableFrom(RepointableActorRef.class));
System.out.println("8: " + ActorRef.class.isAssignableFrom(object.getClass()));
return object instanceof ActorRef; // Always returns false
}
In the above code: 在上面的代码中:
ActorRef
is a Scala abstract class
: ActorRef
是Scala abstract class
:
abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable
RepointableActorRef
is a Scala class
: RepointableActorRef
是Scala class
:
private[akka] class RepointableActorRef extends ActorRef
And ActorRef
is super-class of RepointableActorRef
. 而ActorRef
是超一流的RepointableActorRef
。
When an instance of RepointableActorRef
which is provided by Scala
code (I can't modify it), passed to accept
method, the following output will be printed: 当Scala
代码提供的RepointableActorRef
实例(我无法对其进行修改)传递给accept
方法时,将输出以下输出:
1: class akka.actor.RepointableActorRef
2: class java.lang.Class
3: java.lang.Class - akka.actor.RepointableActorRef
4: false
5: false
6: false
7: true
8: false
So how can i determine a Scala-object's class in Java? 那么如何确定Java中Scala对象的类呢? Or using instance of
correctly ( object instanceof ActorRef
in the above code)? 还是使用正确的instance of
(上面的代码中的object instanceof ActorRef
)?
When an instance of RepointableActorRef which is provided by Scala code (I can't modify it), passed to accept method, the following output will be printed: 当Scala代码提供的RepointableActorRef实例(我无法对其进行修改)传递给accept方法时,将输出以下输出:
No, it won't. 不,不会。 This output means Scala code didn't return an instance of RepointableActorRef
, it returned an instance of Class
, and in particular it returned RepointableActorRef.class
. 此输出表示Scala代码没有返回RepointableActorRef
的实例,而是返回Class
的实例,尤其是返回了RepointableActorRef.class
。
If you want to check whether this instance represents the RepointableActorRef
class, you should compare 如果要检查此实例是否代表RepointableActorRef
类,则应进行比较
RepointableActorRef.class.equals(object)
If you want to check whether it represents a subtype of ActorRef
, it should be 如果要检查它是否代表ActorRef
的子类型,则应为
ActorRef.class.isAssignableFrom((Class<?>) object)
(probably after a check that you got a Class
). (可能在检查您是否获得Class
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.