集册 Java实例教程 强制转换为As的通用方法

强制转换为As的通用方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

447
强制转换为As的通用方法


//package com.nowjava;


public class Main {//来 自 N  o w  J a v a . c o m

    @SuppressWarnings("unchecked")

    /**

     * 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;

        }

    }

}