有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用点表示法解析类属性类型的java

我需要解析支持点表示法的Java类的属性类型。有图书馆可以这样做吗?我正在寻找的方法的签名将如下所示:

getPropertyType(Person.class, "job.phone.areaCode");

共 (1) 个答案

  1. # 1 楼答案

    你可以通过反射来实现。下面的代码基本上使用反射api中的“getDeclaredField”方法来检索所需字段的类型。它通过点符号字段名中的点进行导航

    public static Class<?> getPropertyType(Class<?> clazz, String fieldName) {
        final String[] fieldNames = fieldName.split("\\.", -1);
        //if using dot notation to navigate for classes
        if (fieldNames.length > 1) {
            final String firstProperty = fieldNames[0];
            final String otherProperties =
                StringUtils.join(fieldNames, '.', 1, fieldNames.length);
            final Class<?> firstPropertyType = getPropertyType(clazz, firstProperty);
            return getPropertyType(firstPropertyType, otherProperties);
        }
    
        try {
            return clazz.getDeclaredField(fieldName).getType();
        } catch (final NoSuchFieldException e) {
            if (!clazz.equals(Object.class)) {
                return getPropertyType(clazz.getSuperclass(), fieldName);
            }
            throw new IllegalStateException(e);
        }
    }