确定对象是否是原始类型 [英] Determining if an Object is of primitive type
问题描述
我有一个 Object []
数组,我试图找到那些是原语的。我试过使用 Class.isPrimitive()
,但似乎我做错了什么:
I have an Object[]
array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive()
, but it seems I'm doing something wrong:
int i = 3;
Object o = i;
System.out.println(o.getClass().getName() + ", " +
o.getClass().isPrimitive());
打印 java.lang.Integer,false
。
是否有正确的方式或其他选择?
Is there a right way or some alternative?
推荐答案
Object []
中的类型永远不会真正是原始的 - 因为你有参考!这里 i
的类型是 int
,而 o引用的对象的类型
是整数
(由于自动装箱)。
The types in an Object[]
will never really be primitive - because you've got references! Here the type of i
is int
whereas the type of the object referenced by o
is Integer
(due to auto-boxing).
听起来你需要找到判断该类型是否为原始包装。我认为标准库中没有内置任何内容,但编码很容易:
It sounds like you need to find out whether the type is "wrapper for primitive". I don't think there's anything built into the standard libraries for this, but it's easy to code up:
import java.util.*;
public class Test
{
public static void main(String[] args)
{
System.out.println(isWrapperType(String.class));
System.out.println(isWrapperType(Integer.class));
}
private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes();
public static boolean isWrapperType(Class<?> clazz)
{
return WRAPPER_TYPES.contains(clazz);
}
private static Set<Class<?>> getWrapperTypes()
{
Set<Class<?>> ret = new HashSet<Class<?>>();
ret.add(Boolean.class);
ret.add(Character.class);
ret.add(Byte.class);
ret.add(Short.class);
ret.add(Integer.class);
ret.add(Long.class);
ret.add(Float.class);
ret.add(Double.class);
ret.add(Void.class);
return ret;
}
}
这篇关于确定对象是否是原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!