将对象转换为通用类型以返回 [英] Cast Object to Generic Type for returning

查看:123
本文介绍了将对象转换为通用类型以返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有方法来投射对象来返回方法的值?
我试过这种方式,但它给了一个编译时异常instanceof部分:

Is there a way to cast an object to return value of a method? I tried this way but it gave a compile time exception in "instanceof" part:

public static <T> T convertInstanceOfObject(Object o) {
    if (o instanceof T) {
        return (T) o;
    } else {
        return null;
    }
}



我也尝试了这个,但它给出了一个运行时异常,ClassCastException:

I also tried this one but it gave a runtime exception, ClassCastException:

public static <T> T convertInstanceOfObject(Object o) {
    try {
        T rv = (T)o;
        return rv;
    } catch(java.lang.ClassCastException e) {
        return null;
    }
}

有一种可能的方法: / p>

Is there a possible way of doing this easily:

String s = convertInstanceOfObject("string");
System.out.println(s); // should print "string"
Integer i = convertInstanceOfObject(4);
System.out.println(i); // should print "4"
String k = convertInstanceOfObject(345435.34);
System.out.println(k); // should print "null"



编辑:我写了一个正确答案的工作副本: p>

I wrote a working copy of the correct answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

public static void main(String args[]) {
    String s = convertInstanceOfObject("string", String.class);
    System.out.println(s);
    Integer i = convertInstanceOfObject(4, Integer.class);
    System.out.println(i);
    String k = convertInstanceOfObject(345435.34, String.class);
    System.out.println(k);
}


推荐答案

code> Class 实例由于编译期间的通用类型擦除。

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

声明此方法是:

public T cast(Object o)


$ b b

这也可以用于数组类型。它看起来像这样:

This can also be used for array types. It would look like this:

@SuppressWarnings("unchecked")
final Class<int[]> intArrayType = (Class<int[]>) Array.newInstance(Integer.TYPE, 0).getClass();
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

注意,当 someObject code> convertToInstanceOfObject 它有编译时类型 Object

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

这篇关于将对象转换为通用类型以返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆