2015-05-19 49 views
5

我遇到反射問題。我決定我想用反射創建一個SQL查詢生成器。我創建了自己的註釋來確定可以使用哪些類,可以存儲哪些屬性等。 代碼的工作原理是我想要的,但是在使用這個項目作爲其他項目的依賴時會出現問題。註釋信息的Java反射損失

我有使用OJDBC和IM試圖用我的庫基於類的查詢另一個項目。然而,當我從ojdbc項目傳遞一個類時,所有類信息都會丟失,該類顯示爲java.lang.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方法屬於我的查詢生成器

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)正在失去信息。我已經嘗試生成一個jar中的querybuilder項目,並使用maven安裝將其添加到我的存儲庫,仍然沒有運氣。

感謝您的快速回復,然而這並不是問題,因爲我創建的註釋有保留一套運行時請參閱下文。

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 ""; 
} 

我的註釋設置爲運行時,但類信息仍然丟失。

+0

您發佈應該工作的代碼。也就是說,原因在於別處。你確定傳遞的類對象對應於帶有這個註解的類嗎? (而不是,例如,一些運行時生成的子類?)您確定該類是從具有該註釋的源定義的嗎? (你沒有用沒有註釋的類的舊版本運行,是嗎?) – meriton

+0

不,它使用正確版本的註釋運行,並且此刻沒有子類型。該類不會引發編譯錯誤並正確引用註釋。註解被封裝在一個已經通過Maven依賴關係添加到項目中的jar中。 –

+1

...並且您確定註釋類在運行時類路徑中可用? (你可以通過檢查'Class.forName(「com.whatever.Storable」)'不會拋出異常)來驗證這一點。 – meriton

回答

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(); 
} 
+0

看到我在下面輸入的代碼 –

+0

我不完全確定我在做錯什麼,因爲我做了沒有改變的代碼,現在它似乎運行良好。感謝您的意見。 –