2016-03-14 60 views
1

我有一個SimplePojo類類,我想在使用反射運行時檢索參數修改。獲得參數修改反射

然而,它似乎並沒有工作... SSCEE

public final class SimplePojo { 

    private final String name; 
    private final int age; 

    public SimplePojo(String name, final int age) { 
     this.name = name; 
     this.age = age; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setAge(int age) { 

    } 

    public int getAge() { 
     return age; 
    } 
} 

這就是我如何努力,以檢查是否參數修改爲FINAL

for (Class<?> paramClazz : method.getParameterTypes()) { 
      if (!Modifier.isFinal(paramClazz.getModifiers())) { 
       throw new ConstraintViolationException(
         String.format("Parameters of method '%s' in '%s' must be declared as 'final'", 
           method.getName(), 
           point.getTarget().getClass().getCanonicalName() 
         ) 
       ); 
      } 
     } 

編輯:

//are all constructors params final 
     for (Constructor constructor : clazz.getConstructors()) { 
      for (Class<?> constructorParam : constructor.getParameterTypes()) { 
       Log.e(TAG, "constructorParam:" + constructorParam.getName() + ", mod: " + constructorParam.getModifiers()); 
       if (!Modifier.isFinal(constructorParam.getModifiers())) { 
        throw new ConstraintViolationException(
          String.format("Constructor parameters in '%s' annotated with '%s'" + 
              " must be declared as 'final'", 
            clazz.getCanonicalName(), 
            Inmutable.class.getSimpleName() 
          ) 
        ); 
       } 
      } 
     } 

和輸出:

constructorParam:java.lang.String, mod: 17 
constructorParam:int, mod: 1041 
+1

這是因爲'paramClazz.getModifiers()'正在返回類*的修飾符*,而不是它用作參數。 –

+0

@AndyTurner我不這麼認爲......我已經編輯了代碼,因爲您可以看到修飾符值不同。 – spili

+0

這絕對是如此。 'Class'實例是singleton(每個類加載器),所以'Class.getModifiers()'必須總是返回相同的值 - 它們不依賴於使用該類的上下文,因爲'Class'實例沒有知道的方式。 –

回答

-2

getModifiers返回一組標誌。

試試這個:

final int FINAL = 0x0010; 

if (!(paramClazz.getModifiers() & FINAL)) { 
    throw new ... 
+3

從[JavaDoc for'Modifier.isFinal'](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/ Modifier.html#isFinal(int))「_如果整數參數包含最終修飾符,則返回true,否則返回false ._」OP的代碼(更正確)(比此更正確)。 –

2

假設你使用的是Java 8中,您可以使用Executable.getParameters()方法獲取Method的形式參數。

這將返回一個Parameter實例的數組,您可以在其上調用Parameter.getModifiers()

我不相信有一個標準的Java 8之前的解決方案。

+0

事實上 - 此外,這個「名稱」部分只能使用正確的[編譯器標誌](https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html),並以字節碼爲代價尺寸。 –