开发者

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

I jave a simple Java bean with 4 attributes, gette开发者_如何学Pythonr/setter, and some overided methods like toString, equals and 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

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(). Then iterate the array and for each Field call getAnnotations()

getFields() (and the similar methods) return only the public members.

Anyway, why don't you use JPA, instead of creating your own annotations and annotation processors?


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.

In that case looking at the fields of the Class object at runtime won't tell you the right values (at least not always). Inspecting the return values of the desired methods, however should give the right values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜