Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class<T> and static method Class.forName() drive me crazy

Tags:

People also ask

What is purpose of class forName () method?

forName. Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName ) this method attempts to locate, load, and link the class or interface.

Can you call static method by class object?

Yes we can call static methods using object references. We can call them using object reference as well as class name.

What does the method class forName string className return?

forName(String className) method returns the Class object associated with the class or interface with the given string name.

Why static method is called using its class name in Java?

A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name.


this code doesn't compile. I'm wondering what I am doing wrong:

private static Importable getRightInstance(String s) throws Exception {
 Class<Importable> c = Class.forName(s);
 Importable i = c.newInstance();
 return i;
}

where Importable is an interface and the string s is the name of an implementing class. The compiler says:

./Importer.java:33: incompatible types
found   : java.lang.Class<capture#964 of ?>
required: java.lang.Class<Importable>
  Class<Importable> c = Class.forName(format(s));

thanks for any help!

All the solutions

Class<? extends Importable> c = Class.forName(s).asSubclass(Importable.class);

and

Class<? extends Importable> c = (Class<? extends Importable>) Class.forName(s);

and

Class<?> c = Class.forName(format(s));
Importable i = (Importable)c.newInstance();

give this error (that i don't understand):

Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1 
has interface Importable as super class

where C1 is actually implementing Importable (so it is theoretically castable to Importable).