views:

76

answers:

3

Hi I'm new to java. I'm trying to use some dynamically loaded classes in my application. The application doesn't know classes , Just it try to load a class by name that its name came from input. It doesn't know class (So I can't use casting) but just needs to call some methods of that class (every class should have that methods). I thought about interfaces but I don't know how. How can I call those methods?

Thanks

+3  A: 

Given

Class k = loadMyClassDynamically();

you can

Method m = k.getDeclaredMethod("methodName", ArgClass1.class, ArgClass2.class);

Then, if you create an instance of k

Object ki = k.getDeclaredConstructor().newInstance();

you can call the method on ki

m.invoke(ki, ArgClass3.class, ArgClass4.class);

See the reflection tutorial for details.

Jonathan Feinberg
A: 

Well you'll want to use either interfaces or then a base class from which you inherit. This way you can call a predefined set of methods of the objects you're creating at run-time.

And to get that far you'll probably have to use reflection to create instances based on (text?) input.

JHollanti
Why was this downvoted?
tylermac
Yeah, i concur with tylermac ;)
JHollanti
+1  A: 

Yes, you can use the Class class.

   public InterfaceType getDynamicClass(String className) {
       return (InterfaceType) Class.forName(className).newInstance();
   }

The interface is to ensure that the methods exists. Of course, you'll have to watch out for the exceptions and handle them appropriately for your application.

tylermac