3

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Don Code
  • 781
  • 3
  • 12
  • 25

5 Answers5

5

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())

JHollanti
  • 2,343
  • 8
  • 27
  • 39
  • Thanks, that got the job done. However, I'm wondering why instanceOf wouldn't work. Instance of was my first approach . . – Don Code Apr 14 '13 at 20:03
  • It has to do with which class you mention first and which one last. For example, newEntry.getClass().isAssignableFrom(MyTable.class) wouldn't probably work for you either. Try flipping the arguments and the instanceof should start to work as well. – JHollanti Apr 14 '13 at 20:06
3

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

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

Community
  • 1
  • 1
Srujan Kumar Gulla
  • 5,721
  • 9
  • 48
  • 78
2

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 :)

gaborsch
  • 15,408
  • 6
  • 37
  • 48
2

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()))
Community
  • 1
  • 1
syb0rg
  • 8,057
  • 9
  • 41
  • 81
0

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

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
akostadinov
  • 17,364
  • 6
  • 77
  • 85