Here you can find the source of cast(Class
Parameter | Description |
---|---|
type | A class that indicates the target type. |
obj | An object to be casted. |
T | The target type. |
public static <T> T cast(Class<T> type, Object obj)
//package com.java2s; /*/* w w w. j a v a2s .c o m*/ * Copyright (c) 2014-2015 NEC Corporation * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html */ public class Main { /** * Cast an object type to the specified type. * * @param type A class that indicates the target type. * @param obj An object to be casted. * @param <T> The target type. * @return A casted object if the given object can be casted to the * specified type. Otherwise {@code null}. */ public static <T> T cast(Class<T> type, Object obj) { return (type.isInstance(obj)) ? type.cast(obj) : null; } }