在Java中获取包装类类型的简单方法 [英] Simple way to get wrapper class type in Java

查看:19
本文介绍了在Java中获取包装类类型的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码需要在方法中传递字段的类.由于我的代码的机制,我只能处理引用对象而不是基元.我想要一种简单的方法来确定 Field 的类型是否是原始类型并将其与适当的包装类交换.所以在代码中我到目前为止所做的是这样的:

I have a piece of code where I need to pass the class of a field in a method. Because of the mechanics of my code I can only handle reference objects and not primitives. I want an easy way of determining if a Field's type is primitive and swap it with the appropriate wrapper class. So in code what I do so far is something like this:

Field f = getTheField(); // Dummy method that returns my Field
Class<?> c = f.getType();
if (c == int.class) {
    c = Integer.class;
}
else if (c == float.class) {
    c = Float.class;
}
// etc
myMethod(c);

这很好用,除了我需要显式检查所有原始类型并将它们与适当的包装类交换的事实.现在我知道没有那么多原始类型,简单地列出它们也不是问题,但我想知道是否有一种更简单、更优雅的方法来做到这一点.

This works fine, except for the fact that I need to explicitly check for all the primitive types and swap them with the appropriate wrapper class. Now I know that there are not so many primitive types and it won't be a problem to simply list them all, but I was wondering if there was an easier and more elegant way of doing it.

推荐答案

我在我的回答中使用了 Google Collections Library,因为我被宠坏了,但是如果您愿意,您可能会看到如何使用普通的 HashMap 来做到这一点.

I use Google Collections Library in my answer, because I'm spoiled like that, but you can probably see how to do it with plain HashMaps if you prefer.

  // safe because both Long.class and long.class are of type Class<Long>
  @SuppressWarnings("unchecked")
  private static <T> Class<T> wrap(Class<T> c) {
    return c.isPrimitive() ? (Class<T>) PRIMITIVES_TO_WRAPPERS.get(c) : c;
  }

  private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS
    = new ImmutableMap.Builder<Class<?>, Class<?>>()
      .put(boolean.class, Boolean.class)
      .put(byte.class, Byte.class)
      .put(char.class, Character.class)
      .put(double.class, Double.class)
      .put(float.class, Float.class)
      .put(int.class, Integer.class)
      .put(long.class, Long.class)
      .put(short.class, Short.class)
      .put(void.class, Void.class)
      .build();

奇怪的是,JDK 中没有任何相关内容,但确实没有.

It is odd that nothing exists in the JDK for this, but indeed nothing does.

我完全忘记了我们发布了这个:

I'd totally forgotten that we released this:

http://google.github.io/guava/releases/21.0/api/docs/com/google/common/primitives/Primitives.html

它有 wrap() 方法,加上 unwrap() 和其他一些附带的东西.

It has the wrap() method, plus unwrap() and a few other incidental things.

这篇关于在Java中获取包装类类型的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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