Cast Object by Class - Java Reflection

Java examples for Reflection:Object

Description

Cast Object by Class

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "java2s.com";
        Class tClass = String.class;
        System.out.println(as(obj, tClass));
    }//  w w  w .  ja  v  a2s.  com

    public static <T> T as(Object obj, Class<T> tClass) {
        return tClass.isInstance(obj) ? tClass.cast(obj) : null;
    }
}

Related Tutorials