Using
public class Reflection_Test {
public static void main(String[] args) {
try {
Class c1 = Class.forName("java.util.Date");
Class c2 = Class.forName("Foo");
java.util.Date date = (java.util.Date)c1.newInstance();
Foo foo = (Foo)c2.newInstance();
foo.bar(date);
} catch (Throwable te) {
System.out.println(te);
}
}
}
class Foo {
public void bar(java.util.Date date) {
System.out.println("Hello, world! The date is " + date);
}
}
fixes the compilation errors and
$ javac Reflection_Test.java
$ java Reflection_Test
gives output
Hello, world! The date is Wed Jul 29 15:39:32 CEST 2015
as expected.
The original compilation problem occurred because Class.forName(String className)
is declared to throw a ClassNotFoundException
and the compile-time checking of exceptions in Java requires you to handle this exception (by either catching it or declaring it in the throws clause of the method) as it is a so-called checked exception.
Note: You probably want a slightly more refined approach to error handling than
catch (Throwable te) {
...
}
by catching the specific exception, in particular ClassNotFoundException
(but I was lazy and I augmented the example with creating instances, so there would have been also InstantiationException
and IllegalAccessException
which need to be caught).