5

我有反思的问题。我决定要使用反射创建一个 SQL 查询生成器。我创建了自己的注释来确定可以使用哪些类,可以存储哪些属性等。该代码按我的意愿工作,但是问题在于将此项目用作其他项目的依赖项。

我有另一个使用 OJDBC 的项目,我试图使用我的库来生成基于类的查询。但是,当我从我的 ojdbc 项目中传递一个类时,会丢失所有类信息,该类显示为 java.lang.Class,甚至注释信息也丢失了。有谁知道为什么会这样?

private static <T> void appendTableName(Class<T> cls) throws NotStorableException {
    Storable storable = cls.getAnnotation(Storable.class);
    String tableName = null;
    if (storable != null) {
        if ((tableName = storable.tableName()).isEmpty())
            tableName = cls.getSimpleName();
    } else {    
        throw new NotStorableException(
                "The class you are trying to persist must declare the Storable annotaion");
    }
    createStatement.append(tableName.toUpperCase());
}

cls.getAnnotation(Storable.class)以下类传递给它时正在丢失信息

package com.fdm.ojdbc;

import com.fdm.QueryBuilder.annotations.PrimaryKey;
import com.fdm.QueryBuilder.annotations.Storable;

@Storable(tableName="ANIMALS")
public class Animal {

@PrimaryKey
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

动物类在 ojdbc 项目中,而 appendTableName 方法属于我的查询生成器。我尝试将 querybuilder 项目生成到 jar 中并使用 maven install 将其添加到我的存储库中,但仍然没有运气。

感谢您的快速回复,但这不是问题,因为我创建的注释已将保留设置为运行时,请参见下文。

package com.fdm.QueryBuilder.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = { ElementType.TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Storable {
    public String tableName() default "";
}

我的注释设置为运行时,但类信息仍然丢失。

4

1 回答 1

5

当你想要一个在运行时可用的注解时,你需要向它添加一个注解。

@Retention(RetentionPolicy.RUNTIME)
public @interface Storable {

没有这个,注释在运行时不可见。

有关更多信息,这里是此注释的来源。

/**
 * Indicates how long annotations with the annotated type are to
 * be retained.  If no Retention annotation is present on
 * an annotation type declaration, the retention policy defaults to
 * {@code RetentionPolicy.CLASS}.
 *
 * <p>A Retention meta-annotation has effect only if the
 * meta-annotated type is used directly for annotation.  It has no
 * effect if the meta-annotated type is used as a member type in
 * another annotation type.
 *
 * @author  Joshua Bloch
 * @since 1.5
 * @jls 9.6.3.2 @Retention
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}
于 2015-05-19T16:33:56.053 回答