提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
转换为
/**时代Java公众号 - N o w J a v a . c o m**/ //package com.nowjava; public class Main { public static void main(String[] argv) throws Exception { Class clazz = String.class; Object obj = "nowjava.com"; System.out.println(castAs(clazz, obj)); } public static <T> T castAs(Class<T> clazz, Object obj) { if (obj == null) { return null; } try {/*from 时 代 J a v a - nowjava.com*/ // Try cast. if (clazz.isInstance(obj)) { return clazz.cast(obj); }