[英]How do I get the type of an object so that I can use it with instanceof?
我正在 Java 中編寫一個程序,我有一個帶有 header 的方法,例如public void doSomething(Object o)
我想檢查 o 是否是另一個方法的參數的合適類型。 所以我所擁有的是:
public void doSomething(Object o)
{
Method m = //get method of another method (using reflection)
Class<?> cl = m.getParameterTypes()[0]; //Get the class of the 0th parameter
if(o instanceof cl) //compile error here
//do something
}
然而,這是行不通的。 有人可以幫忙嗎? 謝謝
試試這個:
if(c1.isInstance(o))
{
// ...
}
instanceof
將 static 類型作為參數,您正在尋找的是動態檢查o
是否可以作為該方法的參數;
Object o = ...
Method m = ...
Class cl = m.getParameterTypes()[0];
if(cl.isAssignableFrom(o.getClass())) // Is an 'o' assignable to a 'cl'?
{
}
你可以做
if (o.getClass().equals(cl))
反而。 我相信instanceof
需要實際類型(比如String
而不是String.class
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.