Don Code
Don Code

Reputation: 878

Compare object type

I don't know how to perform type checking on newEntry, I want to make sure that it is of type MyTable (without creating an object of MyTable).

public static boolean add(String table, Object newEntry)
{
    boolean result; 
    if (table.equals("MyTable") && newEntry.getClass() == MyTable.getClass())
    {
         ...
    }   
}

My problem is:

newEntry.getClass() == MyTable.getClass(). 

Note: MyTable is a class name, not an object.

Upvotes: 3

Views: 4802

Answers (5)

Srujan Kumar Gulla
Srujan Kumar Gulla

Reputation: 5841

Use instanceof operator .. Refer to the JLS for more documentation

Check this famous answer What is the difference between instanceof and Class.isAssignableFrom(...)?

Upvotes: 3

syb0rg
syb0rg

Reputation: 8247

Compare with instanceof.

if (newEntry instanceof MyTable) {
    // do something
  }

In this example, the condition is true if newEntry is an instance of MyTable, or if newEntry is an instance of a superclass of MyTable.

Change your statement to this to make it work properly:

if (table.equals("MyTable") && newEntry instanceof MyTable)

You could also use isAssignableFrom() to compare them. The reason you might want to do this is because with instanceof, you have to know the class you are comparing before you compile your program. With isAssignableFrom(), you can change the class you are comparing to during run-time.

if (table.equals("MyTable") && MyTable.class.isAssignableFrom(newEntry.getClass()))

Upvotes: 2

akostadinov
akostadinov

Reputation: 18614

You can use MyTable.class to retrieve the class name.

Upvotes: 0

gaborsch
gaborsch

Reputation: 15758

instanceof is your friend:

if (table.equals("MyTable") && newEntry instanceof MyTable)

It is actually a shorthand for the isAssignableFrom method, but it's much easier to type :)

Upvotes: 2

JHollanti
JHollanti

Reputation: 2413

Basically what you want is:

isAssignableFrom

Take a look at: http://www.ralfebert.de/blog/java/isassignablefrom/

So, in your case, you want:

MyTable.class.isAssignableFrom(newEntry.getClass())

Upvotes: 5

Related Questions