gpt4 book ai didi

java - 反射类型检查?

转载 作者:行者123 更新时间:2023-11-30 05:08:52 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com