简体   繁体   中英

how to call a concrete method of abstract class using reflection in java

public abstract class AbstractClass{

    public String getName(){    
        return " AbstractClass";
    }
}

public class concreteClass extends AbstractClass{
    public String blahBlah(){    
        return " Hi";
    }

}

How to call getName using reflection?

If you have the concreteObject and there are no arguments:

AbstractClass.class.getMethod("getName").invoke(concreteObject);

For more details you could read the java doc of the method in the class Class .

I assume you are asking how to invoke it via reflection without having an instance of AbstractClass ? If that is the question, you cannot do it. To call an instance method of a class (even via reflection) you MUST have an instance on which to invoke the method. Since the method is public, if you DO have an instance you could just call it directly.

Try this:

class MyTest {
     @Test
     public void test1() throws Exception {
         class TestClass extends AbstractClass {
             // implement abstract methods if exists
         }
         Method method = AbstractClass.class.getDeclaredMethod("getName");
         String str = (String) method.invoke(new TestClass());
         assertEquals(" AbstractClass", str);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM