-3

Is something like that possible.

List<?> myList = getMyList();
class cls = class.forname("com.lab.myClass");
cls = myList.get(0);
cls.getValue();

Create an Instance with the fully-qualified name of a class and use their declared Methods?

user3623194
  • 198
  • 1
  • 11
  • 1
    Are you looking for something like [this](http://stackoverflow.com/questions/234600/can-i-use-class-newinstance-with-constructor-arguments)? – logee Aug 03 '15 at 05:40
  • If you have the fully qualified name, you know what type it is. If you know what type it is, just use it directly. – Sotirios Delimanolis Aug 03 '15 at 05:41
  • 1
    did you follow some tutorials about java reflection? you should, it will save you frustration in the future (and now). – hoijui Aug 03 '15 at 05:42

1 Answers1

1

No, if you call Class.forName, at compile time you know nothing about the returned Class instance. You don't even know that it represents a class; it might be an interface for example. In particular, if it is a class and you create an instance of it, you cannot call any methods of it except those which are already defined in Object because, at compile time, the compiler cannot check whether these methods exist.

The are two solutions:

First, you can use reflection to find out about the methods the class has, and to call these methods. This is very cumbersome.

Second, if you use Class.forName to dynamically load classes at runtime, often you know something about the classes you load. For example, you might know that the class implements a certain interface. Then you can cast the result of newInstance to this interface and then call the methods defined in this interface directly.

For example:

// in file Plugin.java
interface Plugin {
    void doSomething();
}

// in file Main.java
public class Main { 
    ...
    void runPlugin() {
        try {
            Class<?> pluginClass = Class.forName("pkg.name.MyPlugin");
            Plugin plugin = (Plugin) pluginClass.newInstance();
            plugin.doSomething();
        }
        catch (...) {
            // catch the necessary exceptions
        }
    }
}
Hoopje
  • 12,677
  • 8
  • 34
  • 50