检查原始字段的类型 [英] Check type of primitive field

查看:104
本文介绍了检查原始字段的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定对象上字段的类型。传递给我时,我不知道对象的类型,但我需要找到 long s的字段。很容易区分盒装 Long ,但原始 long 似乎更难。

I'm trying to determine the type of a field on an object. I don't know the type of the object when it is passed to me but I need to find fields which are longs. It is easy enough to distinguish the boxed Longs but the primitive long seems more difficult.

可以确保传递给我的对象只有 Longs ,而不是原语,但我' d而不是。所以我拥有的是:

I can make sure that the objects passed to me only have Longs, not the primitives, but I'd rather not. So what I have is:

for (Field f : o.getClass().getDeclaredFields()) {
    Class<?> clazz = f.getType();
    if (clazz.equals(Long.class)) {
        // found one -- I don't get here for primitive longs
    }
}

一种似乎有用的hacky方式是:

A hacky way, which seems to work, is this:

for (Field f : o.getClass().getDeclaredFields()) {
    Class<?> clazz = f.getType();
    if (clazz.equals(Long.class) ||  clazz.getName().equals("long")) {
        // found one
    }
}

如果有的话,我真的想要一个更干净的方法。如果没有更好的方法,那么我认为要求我收到的对象只使用 Long (不是 long )是一个更好的API。

I'd really like a cleaner way to do this if there is one. If there is no better way then I think that requiring the objects I receive to only use Long (not long) would be a better API.

任何想法?

推荐答案

你'使用错误的常量来检查Long原语 - 使用 Long.TYPE ,可以在包装器上找到具有类似命名常量的其他原始类型。例如: Byte.TYPE Character.TYPE 等。

You're using the wrong constant to check for Long primitives - use Long.TYPE, each other primitive type can be found with a similarly named constant on the wrapper. eg: Byte.TYPE, Character.TYPE, etc.

这篇关于检查原始字段的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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