简体   繁体   English

如何从Java中的java.lang类型的对象获取对等原始类型?

[英]How to get the equivalement primitive types from an object of java.lang type in Java?

Now is there an easy way to do so? 现在有一个简单的方法吗? Let's say that I have an Object that could be Long, Float, Integer, Byte, etc, how do I get its equivalelent primitive class (Class) from this object? 假设我有一个可能是Long,Float,Integer,Byte等的对象,如何从该对象获取其等效的原始类(Class)?

A method could be written like this 可以这样写一个方法

Class<?> getEquivalentPrimitiveType(Object obj)
{
}

The corresponding primitive type is Long.TYPE : 相应的原始类型为Long.TYPE

public static final Class<Long> TYPE

The Class instance representing the primitive type long . 表示基本类型long的Class实例。

If you have an instance of a "wrapper" class, you can get the corresponding primitive through reflection, like this: 如果您有“包装”类的实例,则可以通过反射获取相应的基元,如下所示:

static <T> Class<T> getPrimitive(Class<T> wrapper)
    throws NoSuchFieldException, IllegalAccessException {
    return (Class<T>)wrapper.getDeclaredField("TYPE").get(null);
}

Here is a demo on ideone . 这是有关ideone演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM