简体   繁体   English

Java反射(和注释):bean.class为空

[英]Java reflection (and annotations): bean.class is empty

I jave a simple Java bean with 4 attributes, getter/setter, and some overided methods like toString, equals and hashCode. 我使用了一个简单的Java bean,它具有4个属性,getter / setter和一些过高的方法,例如toString,equals和hashCode。

Above every Attribute is a custom Annotation: 在每个属性上方是一个自定义注释:

import java.lang.annotation.*;
import java.lang.annotation.RetentionPolicy;

@Target(ElementType.FIELD)
@Retention( RetentionPolicy.RUNTIME )
public @interface DAOProperty {

    String name();
    String type();
    boolean identifier() default false;

}

/** The id. */
@DAOProperty(name = "id", type = "long", identifier = true)
private long id;

If I pass the bean.class to another method 如果我将bean.class传递给另一个方法

generateEntity(User.class);

... ...

private static MEntity generateEntity(Class<?> bean) {...}

and debug it, it seems to bee empty, except for the class name. 并对其进行调试,除了类名外,它似乎是空的。 All arrays like methods, annotations and fields are of zero size. 所有数组(例如方法,注释和字段)的大小均为零。

Where did I go wrong? 我哪里做错了?

Use beanClass.getDeclaredFields() instead of getFields() . 使用beanClass.getDeclaredFields()代替getFields() Then iterate the array and for each Field call getAnnotations() 然后迭代该数组,并为每个Field调用getAnnotations()

getFields() (and the similar methods) return only the public members. getFields() (和类似方法)仅返回公共成员。

Anyway, why don't you use JPA, instead of creating your own annotations and annotation processors? 无论如何,为什么不使用JPA而不是创建自己的注释和注释处理器?

Don't look at the internal fields of the class. 不要看课的内部领域。 They aren't relevant for you. 它们与您无关。 The only thing that should interest you are the return values of the methods. 您唯一感兴趣的是方法的返回值。 It's very likely that java.lang.Class uses those fields to store information that is created on-demand. java.lang.Class很可能使用这些字段来存储按需创建的信息。

In that case looking at the fields of the Class object at runtime won't tell you the right values (at least not always). 在那种情况下,在运行时查看Class对象的字段不会告诉您正确的值(至少不是始终如此)。 Inspecting the return values of the desired methods, however should give the right values. 但是,检查所需方法的返回值应该给出正确的值。

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

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