繁体   English   中英

一种无需使用反射即可获取字段值的方法

[英]A method of getting the value of fields without using reflection

我给了一个包含200个字段的类,其中使用反射来读取它们的值。 基本上看起来像这样

for (Field f : this.getClass().getFields())
        {
            try
            {
                Object o = f.get(this);

                if (f.getType() == String.class)
                {
                    //do things with the string
                }
            }
            catch (Exception ex)
            {
                logger.error("Cannot get value for field. {}", ex.getMessage());
            }

        }

对于我认为是反射点的如此繁琐的场,这非常有效。 我被要求重构它,因为它很慢(是吗?)。

到目前为止,我唯一可以提出他大量的硬编码的方法,还有另一种快速方法吗?

首先,您应该使用探查器来验证它确实很慢。 反射比正常访问变量要慢,但这并不一定意味着它是缓慢的源头。

如果您使用setter来修改这些值,则只要调用setter即可重构该类以更新Map<String,Object> 与反射相比,这提供了对字段的更快访问,但是根据您的用例,可能无法实现。

大部分时间都花费在获取Field对象上(并可能对其进行过滤)。实际查找可能很快。 我使用ClassValue来缓存此信息并加快速度。

public enum StringFields {
    INSTANCE;

    final ClassValue<List<Field>> fieldsCache = new ClassValue<List<Field>>() {
        @Override
        protected List<Field> computeValue(Class<?> type) {
            return Collections.unmodifiableList(
                    Stream.of(type.getFields())
                            .filter(f -> f.getType() == String.class)
                            .peek(f -> f.setAccessible(true)) // turn off security check
                            .collect(Collectors.toList()));
        }
    };

    public static List<Field> getAllStringFields(Class<?> type) {
        return INSTANCE.fieldsCache.get(type);
    }
}

到目前为止,我唯一可以提出他大量的硬编码的方法,还有另一种快速方法吗?

您可以使用反射来获取这些字段的吸气剂并生成读取这些吸气剂的代码。

然后,代码生成可以成为构建步骤的一部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM