Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How get the correct generic type from Class.forName()?

843793Jan 11 2010 — edited Jan 12 2010
I have:
public class Test2 {

    void foo() throws ClassNotFoundException {
        Class<Test2> c = Class.forName("Test2");
}
Of course, this doesn't compile:
javac -Xlint Test2.java
Test2.java:4: incompatible types
found   : java.lang.Class<capture#965 of ?>
required: java.lang.Class<Test2>
        Class<Test2> c = Class.forName("Test2");
Other than casting to Class and suppressing the unchecked warning, how can I get the code to do what I think should be a common use case? I try
public class Test2 {

    void foo() throws ClassNotFoundException {
        Class<Test2> c = Class.forName("Test2").asSubclass(Test2.class);
    }
}
Which doesn't compile either:
javac -Xlint Test2.java
Test2.java:4: incompatible types
found   : java.lang.Class<capture#400 of ? extends Test2>
required: java.lang.Class<Test2>
        Class<Test2> c = Class.forName("Test2").asSubclass(Test2.class);
Not sure I understand what the javac error is about.

Help!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 9 2010
Added on Jan 11 2010
5 comments
2,142 views