Is there something like instanceOf(Class? c) in Java?
Class.isInstance does what you want.
if (Point.class.isInstance(someObj)){
...
}
Of course, you shouldn't use it if you could use instanceof
instead, but for reflection scenarios it often comes in handy.
Using instanceof with a class Object
Use Class.isInstance(obj)
:
public boolean isTypeOf(Class type) {
return type.isInstance(this);
}
This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.
Quoting from the Javadoc:
This method is the dynamic equivalent of the Java language
instanceof
operator.
What is the difference between instanceof and Class.isAssignableFrom(...)?
When using instanceof
, you need to know the class of B
at compile time. When using isAssignableFrom()
it can be dynamic and change during runtime.
Check if an object is an instance of a class (but not an instance of its subclass)
If you have to do this, the only way would be the getClass().equals(Foo.class)
option you've suggested.
However, the goal of OO design is to allow you to treat any Foo
in the same fashion. Whether or not the instance is a subclass should be irrelevant in a normal program.
Is it possible to use the instanceof operator in a switch statement?
This is a typical scenario where subtype polymorphism helps. Do the following
interface I {
void do();
}
class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }
Then you can simply call do()
on this
.
If you are not free to change A
, B
, and C
, you could apply the visitor pattern to achieve the same.
(object instanceof C) what is the type of C?
You can use the isInstance
method of Class
.
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language
instanceof
operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
So you would write
if (objClass.isInstance(obj)) ...
If you want to do this generically, you can use .cast
to convert to the type represented by objClass
.
public <T> void method(Object obj, Class<T> objClass) {
if(objClass.isInstance(obj)) {
T t = objClass.cast(obj);
//do something with t instead of obj
}
}
How to check if a subclass is an instance of a class at runtime?
You have to read the API carefully for this methods. Sometimes you can get confused very easily.
It is either:
if (B.class.isInstance(view))
API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)
or:
if (B.class.isAssignableFrom(view.getClass()))
API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter
or (without reflection and the recommended one):
if (view instanceof B)
How instanceof will work on an interface
First of all, we can store instances
of classes that implements a particular interface
in an interface reference variable
like this.
package com.test;
public class Test implements Testable {
public static void main(String[] args) {
Testable testable = new Test();
// OR
Test test = new Test();
if (testeable instanceof Testable)
System.out.println("instanceof succeeded");
if (test instanceof Testable)
System.out.println("instanceof succeeded");
}
}
interface Testable {
}
ie, any runtime instance that implements a particular interface will pass the instanceof
test
EDIT
and the output
instanceof succeeded
instanceof succeeded
@RohitJain
You can create instances of interfaces by using anonymous inner classes like this
Runnable runnable = new Runnable() {
public void run() {
System.out.println("inside run");
}
};
and you test the instance is of type interface, using instanceof
operator like this
System.out.println(runnable instanceof Runnable);
and the result is 'true'
How to determine an object's class?
if (obj instanceof C) {
//your code
}
Check if an object is instance of List of given class name
Ok, I found a method... it's a little dirty code but it works:
if (o instanceof List<?>){
ParameterizedType pt = (ParameterizedType)o.getClass().getGenericSuperclass();
String innerClass = pt.getActualTypeArguments()[0].toString().replace("class ", "");
System.out.println(innerClass.equals(className)); // true
}
Related Topics
Extract Integer Part in String
Number of Decimal Digits in a Double
How to Change the Color of Specific Words in a Jtextpane
Eventlisteners Using Hibernate 4.0 with Spring 3.1.0.Release
Why Aren't Integers Cached in Java
Java Byte Array Contains Negative Numbers
How Can a Keylistener Detect Key Combinations (E.G., Alt + 1 + 1)
Why Should I Override Hashcode() When I Override Equals() Method
How to Set Order of Repositories in Maven Settings.Xml
Differencebetween String and Stringbuffer in Java
Convert Two Dimensional Array to List in Java
Jaxb :Need Namespace Prefix to All the Elements
Enable Partial Compilation in Intellij Idea
Using PDFbox to Write Utf-8 Encoded Strings to a PDF
Extended Server_Name (Sni Extension) Not Sent with Jdk1.8.0 But Send with Jdk1.7.0