java - 反射类型检查?

标签 java reflection types

我想找到一种方法来动态检查字符串是否可以解析为给定类型。 换句话说,

public boolean canBeParsed(String type, String val) {
    // use reflect to check if val can be parsed into type
}

显然,我希望能够检查具有不同值的不同类型..

类型将是字符串,例如:Java.lang.Integer

----------加法-------------

例如,如果我调用这个函数,

canBeParsed("Java.lang.Integer", "1"); //returns true

canBeParsed("Java.lang.Integer", "HelloWorld"); //returns false

canBeParsed("Java.lang.String", "HelloWorld"); //returns true

canBeParsed("Java.lang.Boolean", "false"); // returns true

canBeParsed("Java.lang.Boolean", "HelloWorld"); //returns false

最佳答案

此方法适用于声明静态 valueOf 方法的类。任何没有这个的类都会返回 false。为了保持代码简短,省略了几个异常。

Class<?> cls = Class.forName(type);
//Get a converter method, String to  type
//Requires static method valueOf
Method converter;
try{
converter = cls.getDeclaredMethod("valueOf",new Class[]{String.class});
}catch(NoSuchMethodError ex){
   //No conversion method found
   return false;
}
if(!Modifier.isStatic(converter.getModifiers()){
   //the method has to be static in order to be called by us
   return false;
}
if(!cls.isAssignableFrom(converter.getReturnType())
    //The conversion method has the wrong return type
    return false;
try{
    //try to parse the value
    Object o = converter.invoke(null,new Object[]{value};
    if( o == null)return false;//false if method returned null
    else return true;//success
}catch(Exception ex)
{
    //could not parse value
    return false;
}

valueOf(String) 方法存在于包装类 Short、Long、Integer、Float、Double、Boolean 中,因此它支持这些类以及具有此方法的任何其他类。

关于java - 反射类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174188/

相关文章:

java - JUnit Mockito URL 和 HttpsURLConnection

java - 为什么 java.io.File.listFiles() 抛出 NPE 而不是正确的异常?

java - 设置公共(public)成员时出现 IllegalArgumentException

c# - 静态类中的匿名方法是非静态的?如何调用它?

scala - 是否可以通过创建诸如PositiveInt之类的东西来限制Int并在Scala中进行编译时检查?

java - GNU 的 Java 编译器 (GCJ) 死了吗?

Java 有没有可以将 SQL 语句提取到文件中的 IDE/工具?

c# - 使用activationCustomData参数创建类实例

types - BSTR,如何制作自己的?

c++ - 如何检查类型是否是 C++ 中模板类的类型参数?