簡體   English   中英

如何獲取 object 的類型以便我可以將它與 instanceof 一起使用?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM