Java Reflection - Class.cast() Examples

Code Snippets Java Reflection Java 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public T cast(Object obj)

This method casts an object to the class or interface represented by this Class object.

Parameters:
obj - the object to be cast
Returns:
the object after casting, or null if obj is null

Examples


package com.logicbig.example.clazz;

import java.util.HashSet;
import java.util.LinkedHashSet;

public class CastExample {

public static void main(String... args) {
LinkedHashSet<String> lhs = new LinkedHashSet<>();
HashSet hs = HashSet.class.cast(lhs);
System.out.println(hs.getClass());
}
}

Output

class java.util.LinkedHashSet




package com.logicbig.example.clazz;

public class CastExample2 {

public static void main(String... args) {
Sup sup = new Sup();
Sub sub = safeCastTo(sup, Sub.class);
System.out.println(sub);

Sub sub2 = new Sub();
Sup sup2 = safeCastTo(sub2, Sup.class);
System.out.println(sup2);

Other other = new Other();
Sup sup3 = safeCastTo(other, Sup.class);
System.out.println(sup3);
}

public static <T> T safeCastTo(Object obj, Class<T> to) {
if (obj != null) {
Class<?> c = obj.getClass();
if (to.isAssignableFrom(c)) {
return to.cast(obj);
}
}
return null;
}

public static class Sup {
}

public static class Sub extends Sup {
}

public static class Other {

}
}

Output

null
com.logicbig.example.clazz.CastExample2$Sub@1e357e9c
null




See Also