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

查看:111
本文介绍了在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,因为我被这样宠坏了,但如果你愿意的话,你可能会看到如何使用普通的HashMaps。

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天全站免登陆