A smart way to test a superclass

public boolean isUserControled(){ return action.getClass().getSuperclass().toString().equals("class logic.UserBehaviour"); } 

I think this piece of code is pretty straightforward. Is there a smarter way to do this?

thanks

+7
source share
3 answers

Unless you specifically want to check only the first superclass, it would be better to use:

 return (action instanceof logic.UserBehavior); 

Your method will be better with this:

 action.getClass().getSuperClass().name().equals("logic.UserBehavior"); 

Calling toString() is not a good idea.

Or better yet, as published by Ulrik :

 action.getClass().getSuperClass() == logic.UserBehavior.class 
+9
source

(action instanceof logic.UserBehaviour) will return true if the action is an object of a type that extends UserBehavior.

Excerpt from http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

InstanceOf type comparison operator

The instanceof operator compares the object to the specified type. You can use it to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (called MyInterface), and a child class (called Child) that inherits from the parent and implements the interface.

 class InstanceofDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); } } class Parent{} class Child extends Parent implements MyInterface{} interface MyInterface{} 

Output:

 obj1 instanceof Parent: true obj1 instanceof Child: false obj1 instanceof MyInterface: false obj2 instanceof Parent: true obj2 instanceof Child: true obj2 instanceof MyInterface: true 

When using the instanceof operator, keep in mind that null is not an instance of anything.

+11
source

If you want to check only the first superclass:

 return action.getClass().getSuperclass() == logic.UserBehavior.class; 

Otherwise:

 return (action instanceof logic.UserBehaviour); 
+5
source

All Articles