Java如何检查字符串值是否是给定类的类型<?> [英] Java how to check if a string value is a type of given Class<?>

查看:129
本文介绍了Java如何检查字符串值是否是给定类的类型<?>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧这是一个复杂的问题而且我完全迷失了。

Alright this is kind of a complicated question and I'm completely lost.

假设你有一个字符串和一个泛型类。像这样。

Assume you have a string, and a generic class. Like this.

String string;
Class<?> clazz;

您如何检查String是否代表该类可以相等的值。

How would you check to see if the String represented a value that the class could equal.

例如,假设:

String string = "true";
Class<?> clazz = Boolean.class;

我如何检查并看到字符串true实际上是一个布尔值?

How would I check and see that the string "true" is in fact a boolean?

这是另一个例子。让我们说:

Here is another example. Lets say that:

String string = "true";
Class<?> clazz = Integer.class;

我如何查看字符串true不是整数?

How would I check and see that the string "true" is not an Integer?

推荐答案

鉴于你只想要 Wrapper Types ,你可以在这里使用一些反射黑客(不相关的异常处理)为简洁起见,此处忽略代码):

Given that you want this only for Wrapper Types, you can use some reflection hack here (Exception handling for irrelevant code is ignored here for brevity):

String string = "ABC";
Class<?> clazz = Integer.class;

Method method = clazz.getDeclaredMethod("valueOf", String.class);

if (method != null) {
    try {
        Object obj = method.invoke(null, string);       
        System.out.println("Success : " + obj);

    } catch (InvocationTargetException ex) {
        System.out.println("Failure : " + string + " is not of type " + 
                                          clazz.getName());
    }
}

我考虑到每一个事实wrapper类有一个 static valueOf 方法,它接受类型为 String 的参数,并返回该包装器类型的值。如果参数不能转换为相应的包装器类型,则抛出异常。

I'm taking into account the fact that, every wrapper class has a static valueOf method that takes a parameter of type String, and returns the value of that wrapper type. And throws an exception, if the parameter is not convertible to the respective wrapper type.

因此,在上面的情况下,如果抛出异常, string 值不是 clazz 类型。

So, in above case, if an exception is thrown, the string value is not of clazz type.

PS:请注意,对于 Boolean.class ,任何不是true的字符串都将被视为 false

P.S.: Note that for Boolean.class, any string that is not "true" will be treated as false.

这篇关于Java如何检查字符串值是否是给定类的类型&lt;?&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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