2

I have a string com.bar.Baz. I want to get Class<T>, where T is anything that extends an interface com.bar.Foo from the string.

Here is what I have tried but, it allows any class type, which is wrong.

Updated:(Based on the comment)

@SuppressWarnings("unchecked")
    public static <T extends Foo> Class<T> getClassOfTypeT(String clazz) {
        Class<T> ruleType = null;
        try {
            ruleType = (Class<T>) Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            logger.error("Can't cast " + clazz, e);
        }
        return ruleType;
    }


    public static void main(String[] args) {
        System.out.println(getClassOfTypeT("java.lang.String"));//Should not be allowed
    }

How to get Class<T> from a string?

phoenix
  • 985
  • 3
  • 17
  • 38
  • 1
    First, let's use proper terminology; this method is not casting. – Oliver Charlesworth Dec 12 '14 at 08:25
  • Second, bear in mind that generics are erased at runtime. So you effectively just have `ruleType = (Class)Class.forName(clazz);`. – Oliver Charlesworth Dec 12 '14 at 08:28
  • See http://stackoverflow.com/questions/3504870/how-to-test-if-one-java-class-extends-another-at-runtime. – Oliver Charlesworth Dec 12 '14 at 08:30
  • @OliverCharlesworth I strongly feel that this is not a duplicate. Help me understand how it is duplicate? I want to get an instance of Class from string right? – phoenix Dec 12 '14 at 08:34
  • 1
    Yes, but you've solved that bit already. The bit you're currently dealing with is checking whether it extends from Foo. – Oliver Charlesworth Dec 12 '14 at 08:36
  • @OliverCharlesworth Thanks. Then, I think you can state the same as answer and remove duplicate. Because my question is different. – phoenix Dec 12 '14 at 08:40
  • 1
    Your *problem* is identical. Your *question* happens to also talk about something you're already solved ;) – Oliver Charlesworth Dec 12 '14 at 08:43
  • Yes, @OliverCharlesworth is right. Your question finishes with "*How to get `Class` from a string?*", whereas it should say "*How do I ensure `ruleType` extends `Foo`?*" In which case, the duplicate is correct. – Duncan Jones Dec 12 '14 at 08:59

0 Answers0