generic method to cast As - Java Object Oriented Design

Java examples for Object Oriented Design:Method Parameter

Description

generic method to cast As

Demo Code


//package com.java2s;

public class Main {
    @SuppressWarnings("unchecked")
    /**/*w w w  .  j a va 2 s  .  c o m*/
     * Attempt casting passed in object as the type of class C.
     * Will return null if the cast is incompatible rather then
     * throw an exception.
     * 
     * @param object
     * @param c
     * @return
     */
    public static <T> T castAs(Object object, Class<T> c) {
        try {
            return (T) object;
        } catch (Exception e) {
            return null;
        }
    }
}

Related Tutorials