Reputation: 3049
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
:
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
:
abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable
RepointableActorRef
is a Scala class
:
private[akka] class RepointableActorRef extends ActorRef
And ActorRef
is super-class of 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:
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? Or using instance of
correctly (object instanceof ActorRef
in the above code)?
Upvotes: 0
Views: 184
Reputation: 170919
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:
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
.
If you want to check whether this instance represents the RepointableActorRef
class, you should compare
RepointableActorRef.class.equals(object)
If you want to check whether it represents a subtype of ActorRef
, it should be
ActorRef.class.isAssignableFrom((Class<?>) object)
(probably after a check that you got a Class
).
Upvotes: 1