Java检查Java本机对象是否没有默认值,或者是否实例化它

问题描述 投票:-2回答:1

我已检查“ Java本机对象是否没有默认值”。请注意:如果它们不是'null',我必须忽略自定义对象的值

/**
 * This method will check if given object is used by given testConfig file 1. if
 * instance of {@link String}, and it's value shouldn't be 'empty' or 'null'. 2.
 * if instance of {@link Integer}, and it's value shouldn't be '0'(zero). 3. if
 * instance of {@link Boolean}, and it's value shouldn't be 'false'. 4. if
 * instance of any non-null {@link Object}
 * 
 * @param method  tag name in the form of 'getter method'
 * @param objName given 'getter method' return type
 * @return list of used tags
 */
private List<String> isUsedTag(Method method, Object objName) {
    List<String> usedTags = new ArrayList<>();
    if (objName != null && (((objName instanceof Integer) && (!isNullorZero((Integer) objName)))
                    || ((objName instanceof String) && (!Util.isAnyNullOrEmpty((String) objName)) && !((String)objName).equalsIgnoreCase("0"))
                    || ((objName instanceof Boolean) && ((Boolean) objName))
                    || ((objName instanceof Object) && !(objName instanceof Boolean))
                    || ((objName instanceof List) && !Util.isEmpty((List)objName))
                    || ((objName.getClass().isPrimitive()) && (Integer.valueOf((int)objName) != 0))
            )) {
        usedTags.add(method.getName());
    } 
    return usedTags;
}

并且检查Integer对象是否为'0'方法是

/**
 * Checks whether given 'Integer' Object is non-null/non-zero
 * @param i
 * @return true if given integer value is '0'
 */
public static boolean isNullorZero(Integer i){
    return 0 == ( i == null ? 0 : i);
}

有什么更好的方法可以做到这一点吗?🤔

java object reflection
1个回答
0
投票

我重构了如下代码

private List<String> isUsedTag(Method method, Object objName) {
    List<String> usedTags = new ArrayList<>();
    if (objName != null && ((objName instanceof Object && !isDefaultObj(objName))
            || (isDefaultObj(objName) && !isDefaultValue(objName)))) {
        usedTags.add(method.getName());
        System.out.println(method.getReturnType() + " " + method.getName() + " ---> " + objName);
    } else {
        System.out.println("UnUsed :: " + method.getReturnType() + " " + method.getName() + " :: " + objName);
    }
    return usedTags;
}

public boolean isDefaultValue(Object objName) {
    return (((objName instanceof Integer) && isNullorZero((Integer) objName))
            || ((objName instanceof String) && (Util.isAnyNullOrEmpty((String) objName))
                    && ((String) objName).equalsIgnoreCase("0"))
            || !((objName instanceof Boolean) && (Boolean) objName));
}

public boolean isDefaultObj(Object objName) {
    return ((objName instanceof Integer) || (objName instanceof String) || (objName instanceof Boolean));
}

public static boolean isNullorZero(Integer i){
    return 0 == ( i == null ? 0 : i);
}
© www.soinside.com 2019 - 2024. All rights reserved.