2010-05-22 20 views
0

我試圖製作一個方法,其參數爲Country.classUser.class等,並返回argument.count()在Java中傳遞一個類(「Country.class」)作爲參數

我給這個方法的所有可能的類從Model延伸並且具有方法count()

我的代碼:

private static long <T> countModel(Model<T> clazz) 
{ 
    // there is other important stuff here, which prevents me from 
    // simply by-passing the method altogether. 

    return clazz.count(); 
} 

通過調用:

renderArgs.put("countryCount", countModel(Country.class)); 

但是,這是行不通的。

請問我該怎麼做?

+0

我不明白你在問什麼,'Country.class'是'Class',並沒有任何'count()'。你能用簡單的英語來重述你的問題嗎? – 2010-05-22 20:36:46

+1

你除了有一個特定的靜態方法的類嗎?這是一個非常奇怪的設計。 – whiskeysierra 2010-05-22 21:51:38

回答

5

我想你想要做的

private long countModel(Class<? extends Model> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException 
{ 
    Method countMethod = clazz.getDeclaredMethod("count", null); 
    return (Long) countMethod.invoke(null, null); 
} 

希望像這樣的工作(我的反思能力是不是真的那麼好)。

+0

這就是它!只需要拿出「空」的參數,它的工作。謝謝。 – 2010-05-22 20:53:46

2

不完全理解你想達到的目標。你的意思是?

private static long <T> countModel(Model<T> model) 
{ 
    return model.count(); 
} 

renderArgs.put("countryCount", countModel(country)); 

編輯:如果count是一個靜態方法,它與模型無關。靜態方法不被繼承。因此,所有你所要做的就是直接調用它,

renderArgs.put("countryCount", Country.count()); 
+0

不,這些類有'count()'作爲靜態方法,而不是對象。對不起,如果我不清楚。 – 2010-05-22 20:16:21

+0

看到我的編輯.... – 2010-05-22 20:22:18

+0

第一部分甚至沒有編譯,所以我不認爲這是OP的意思:) – 2010-05-22 20:44:46

0

在行

renderArgs.put("countryCount", countModel(Country.class)); 

你叫countModelClass<Country>,但你必須與Country這樣一個實例來調用它:

Country country = new Country(); 
renderArgs.put("countryCount", countModel(country); 
-1

你傳入Country.class這是一個Class對象。它是怎樣的一個Model對象?

0

您還沒有經過國家的一個實例,在這裏,你傳遞一個Class對象:

renderArgs.put("countryCount", countModel(Country.class)); 

您需要實例化一個模型,並將其作爲參數傳遞:

 

Model model = new Country(); 
renderArgs.put("countryCount", countModel(model)); 
 

 

Country country = new Country(); 
renderArgs.put("countryCount", countModel(country)); 
 

在這種情況下,Country.classClass<Country>類型的一個對象。

0

回覆您對ZZ編碼器的評論; Java中的靜態方法被稱爲一類的名稱空間上下文,像Model.count()在類Model靜態方法count(),但該方法不成爲Model.class一部分,Model.classClass描述類Model一個實例。 (我能看到的混亂起源,這將是合乎邏輯的有一個專門的Model.class包括靜態方法,但Java未能desinged這樣的。)

你的出路就是使用反射來調用靜態count()對於你傳遞給你的代碼的類。

1

澄清,你想要的被約束的一類(A)爲具有特定的類的方法(B)和要傳遞該類作爲參數傳遞給一些其它方法(C),並且具有該方法(C)調用那班的那個班級方法(A.B())?

第一部分,類型約束,不能完成。 Java的類型系統不會那樣工作。

第二部分,傳遞一個類作爲參數並調用它的一個類方法,即可以使用反射完成。這就是如何做到這一點,從你的代碼中糾正(儘管你應該比例外情況更加小心)。

private static <T extends Model> long countModel(Class<T> clazz) throws Exception 
{ 
    return (Long) clazz.getMethod("count").invoke(null); 
} 

null是調用該實例上(沒有實例,它是一個類的方法)。由於invoke()Object,因此需要投射到Long。類型參數必須位於結果類型之前。整個事件可以採用的任何類作爲Model的子類作爲參數;如果count方法不存在,它只會在運行時失敗。他們的休息。 (也請注意,如果您想將參數傳遞給count(),則必須將這些參數的類別指定爲getMethod,並將這些值本身指定爲invoke,這兩種情況都作爲後續參數。兩者均支持Java5可變參數列表)

+0

謝謝,這個工程。 frosty_hotboy是第一次,所以我給他打勾。 – 2010-05-22 20:56:12