Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

java - Checking if object is instanceof Class in function, which takes Class as parameter

I am learning RTTI in Java and I wrote a function like that:

static void select(Shape s, Class c)
{
   if(s instanceof c)
   s.setSelected(true);
}
//Calling function: select(shape0, Circle);

The problem is, I have no idea if passing Class as paremater is possible? Compilator says it's error, it can't find c. So I used different code to solve this problem:

static void select(Shape s,Object obj)
{
    if(s.getClass().equals(obj.getClass()))
    s.setSelected(true);
}
 //Calling function: select(shape0, new Circle());

But I was wondering if something like first example is possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the isInstance or isAssignableFrom method of Class depending on your needs.

isInstance docs excerpt:

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

isAssignableFrom docs excerpt:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...