Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determining if a Class object is an instance of an abstract class

I'm trying to determine if a generic class object is an instance of an abstract class. So far I'm not having much luck. Below is the code I'm trying to use. AbstractActivity is the name of a parent class I extend some of my activities from.

public void startActivity(Intent intent)
{
    ComponentName name = intent.getComponent();

    if(name != null)
    {
        Class<?> cls = null;
        try {
            cls = Class.forName(name.getClassName());

            if(cls.isInstance(AbstractActivity));
            {
                //do something
            }
            else
            {
                super.startActivity(intent);
            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    super.startActivity(intent);
}
like image 688
iHorse Avatar asked Dec 20 '10 23:12

iHorse


People also ask

How do you check if an object is an instance of a particular class?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

How do you know if its an abstract class?

An abstract class has at least one abstract method. An abstract method will not have any code in the base class; the code will be added in its derived classes.

Can you have an instance of an abstract class?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.

How do you find the concrete method of an abstract class?

The only way to access the non-static method of an abstract class is to extend it, implement the abstract methods in it (if any) and then using the subclass object you need to invoke the required methods.


1 Answers

I would try:

if(AbstractActivity.class.isAssignableFrom(cls)) {
    ....
}
like image 139
Kevin Gaudin Avatar answered Sep 22 '22 11:09

Kevin Gaudin