如何将Java中的类型与反射进行比较
I have following code and now I have type, but I need to have some kind of switch to know if type is for example of String and then do handling for strings. So how can I check if Type t is type of String?
我有以下代码,现在我有类型,但我需要有一些切换,以知道类型是否为例如String,然后处理字符串。那么如何检查Type t是否为String类型?
Type t = bean.getClass().getDeclaredField(fieldName).getType();
1 个解决方案
#1
10
Do you want to do a name check or an object-based check?
您想进行名称检查还是基于对象的检查?
Since Class
implements Type
, you can actually go directly and do the equals against String.class
For instance: if (t.equals(String.class))
由于Class实现了Type,你实际上可以直接去String.class做等于例如:if(t.equals(String.class))
If, however, you want to do a check based on name, then first check if t is an instance of Class, and then cast it to Class, obtain the full type name, and compare.
但是,如果要根据名称进行检查,则首先检查t是否为Class的实例,然后将其强制转换为Class,获取完整的类型名称,然后进行比较。
更多相关文章
- “checkout as maven project from scm”中缺少scm类型
- Spring Hibernate:没有类型为org.hibernate.SessionFactory的匹配
- dom4j-java-如何获取root中具有特定元素名称的所有元素(父元素或
- java返回值是list的时候获取list的参数类型
- 如何知道Object是否为String类型对象?
- 如何让BlockingQueue接受多种类型?
- 当只使用get()和set()方法时,用原始类型替换AtomicBoolean?
- Java中的数据类型
- Java反射---getGenericSuperclass和ParameterizedType参数化类型