【问题标题】:Read annotation value from interface?从接口读取注释值?
【发布时间】:2014-02-04 14:46:38
【问题描述】:

我正在开发一个框架,允许开发人员通过服务层进行数据库操作。服务类将发送数据库请求 dto 对象,该对象将使用 sql ID 进行注释,以用作 MyBatis 中的 ID。稍后我会通过反射读取注解值。

首先,我创建了一个自定义的注解界面。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyBatisMapper {
    String namespace() default "";
    String sqlId() default "";
}

以及数据库请求dto对象的接口。

public interface IReqDto {    
    public String getDaoType();
}

以及实现上述IReqDto接口的数据库请求dto对象。

@MyBatisMapper(namespace="User", sqlId="userInsert")
public class UserInsertReqDto implements IReqDto{
    //beans and getters/setters
}

上述 bean 可能会根据开发人员的要求而有所不同。这不是框架的一部分。开发者必须在他使用的任何类型的数据库请求对象中实现IReqDto 接口。

我正在尝试使用反射从数据库调用程序类中读取带注释的值 (namespace and sqlId)。

我知道这样做可以得到带注释的值。

Class<UserInsertReqDto> ReqDto = UserInsertReqDto.class;        
for(Annotation annotation : ReqDto.getAnnotations()) {
    System.out.println(annotation.toString());
}

但我的问题是,由于UserInsertReqDto 会有所不同,我尝试对IReqDto 接口使用反射。

Class<IReqDto> ReqDto = IReqDto.class;

好吧,这肯定行不通。 问题是 - 在这种情况下如何从数据库请求对象中读取带注释的值?谢谢。

【问题讨论】:

  • 只有存在注解才能获取注解。 UserInsertReqDto 有注释,IReqDto 没有。不清楚你在问什么。
  • @SotiriosDelimanolis 抱歉,问题未解。 UserInsertReqDto 只是一个例子。这只会在框架的用户创建它时存在。我必须在框架中准备好获得实现IReqDto 的任何ReqDto 类的注释。先生,感谢您的宝贵时间。

标签: java reflection annotations


【解决方案1】:

也许我还是误解了你的问题,如果有必要请纠正我。

您将获得ReqDto 的自定义实现的对象

ReqDto object = ...; // get instance
Class<?> clazz = object.getClass(); get actual type of the instance

for(Annotation annotation : clazz.getAnnotations()) { // these are class annotations
    System.out.println(annotation.toString());
}

MyBatisMapper mapperAnnotation = clazz.getAnnotation(MyBatisMapper.class);
if (mapperAnnotation != null) {
    System.out.println(mapperAnnotation.namespace()
    System.out.println(mapperAnnotation.sqlId()
}

【讨论】:

    【解决方案2】:

    无论类型如何,反射都有效。因此,不要引用具体类,只需使用Object#getClass() 和/或Class&lt;?&gt;。例如

    public Metadata getMetadata(Object pojo) {
       Annotation annotation = pojo.getAnnotation(MyBatisMapper.class);
       if (annotation == null) {
          return null;
       }
       return new Metadata(annotation.getNamespcae(), annotation.getSqlId());
    }
    

    其中Metadata 只是一个值类,您可以稍后使用它,其中包含有关对象的值。您也可以直接使用MyBatisWrapper 注解。

    【讨论】:

    • 只需修复 annotation 变量的声明类型。还有pojo.getClass().getAnnotation..
    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2022-11-28
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多