Results 1 to 4 of 4
- 12-02-2011, 05:50 PM #1
Member
- Join Date
- Oct 2011
- Posts
- 90
- Rep Power
- 0
Dynamically call inherited method
Hi, I have an abstract super class and several sub classes that inherit from it. I need to dynamically pick which class AND which method I use at runtime. Unfortunately I am getting a java.lang.NoSuchMethodException: TestChildClass.getI(). As TestChildClass is a child of TestClass and TestClass.getI() does exist, I assume I may need something else. Thanks!
Java Code:import java.lang.reflect.Method; public class TestClass { protected static int i; public static int getDynamicMethod(String className, String methodName) { try { Class messageClass = Class.forName(className); Method classMethod = messageClass.getDeclaredMethod(methodName, null); return (Integer) classMethod.invoke(null); } catch(Exception ex) { ex.printStackTrace(); } return -1; } public static int getI() { return i; } public static void main(String[] args) { int testI = TestClass.getDynamicMethod("TestChildClass", "getI"); System.out.println(testI); } } class TestChildClass extends TestClass { public TestChildClass() { i=0; } }Last edited by joeyvitoro; 12-02-2011 at 06:13 PM.
- 12-02-2011, 06:10 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,383
- Blog Entries
- 7
- Rep Power
- 17
Re: Dynamically call inherited method
If the methods aren't static, the first parameter of the invoke( ... ) call can never be null. If the method doesn't take arguments, leave out the second null parameter.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-02-2011, 06:14 PM #3
Member
- Join Date
- Oct 2011
- Posts
- 90
- Rep Power
- 0
Re: Dynamically call inherited method
Jos,
Thanks for the reply. I have made these changes and I still get the same error.
- 12-02-2011, 07:37 PM #4
Member
- Join Date
- Oct 2011
- Posts
- 90
- Rep Power
- 0
Similar Threads
-
Inherited actionPerformed method
By doobybug in forum New To JavaReplies: 4Last Post: 08-13-2011, 11:33 AM -
Dynamically create objects, set value and call
By buntyindia in forum New To JavaReplies: 5Last Post: 05-25-2011, 05:59 PM -
Inherited method that returns string
By Xeal Rebad in forum New To JavaReplies: 5Last Post: 05-23-2011, 01:26 PM -
Inherited method returning bad value
By viking90 in forum New To JavaReplies: 11Last Post: 04-07-2010, 03:53 PM -
Create, compile and call a Java source dynamically
By Java Tip in forum Java TipReplies: 0Last Post: 02-17-2008, 08:57 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks