cast As - Java Reflection

Java examples for Reflection:Method

Description

cast As

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        Object obj = "java2s.com";
        System.out.println(castAs(clazz, obj));
    }//from w ww. ja v a  2s  .  co m

    public static <T> T castAs(Class<T> clazz, Object obj) {
        if (obj == null) {
            return null;
        }

        try {
            // Try cast.
            if (clazz.isInstance(obj)) {
                return clazz.cast(obj);
            }

        } catch (ClassCastException ex) {
            // No op.
        }

        return null;
    }
}

Related Tutorials