我可以将feebhashmap用于班级的缓存字段吗?
由于某种原因,我需要使用反射来缓存类及其字段或字段名称的条目。
private static final Map<Class<?>, String> ID_ATTRIBUTE_NAMES = new WeakHashMap<>();
private static String findIdAttributeName(final Class<?> clazz) {
Objects.requireNonNull(clazz, "clazz is null");
for (Class<?> current = clazz; current != null; current = current.getSuperclass()) {
for (final Field field : current.getDeclaredFields()) {
if (field.getAnnotation(Id.class) != null) {
return field.getName();
}
if (field.getAnnotation(EmbeddedId.class) != null) {
return field.getName();
}
}
}
throw new RuntimeException("unable to find an id attribute from " + clazz);
}
private static String idAttributeName(final Class<?> clazz) {
Objects.requireNonNull(clazz, "clazz is null");
return ID_ATTRIBUTE_NAMES.computeIfAbsent(clazz, BaseMappedHelper::findIdAttributeName);
}
我之所以没有将映射定义为 map&lt; class&lt;?
除了使用 String
的字段名称外,还有其他方法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用apache或spring beanutils( https://commons.apache.org/proper/commons/commons/commons/commons -Beanutils/)通过缓存进行了优化。
也许您需要BeanMap与对象作为地图进行交互。
,
但是您不需要弱参考不是那么巨大。
You can use Apache or Spring BeanUtils (https://commons.apache.org/proper/commons-beanutils/) that is optimized with cache.
Maybe you need BeanMap to interacte with your objects as map.
https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/BeanMap.html
But you don't need a weak reference because number of fields is not so huge.