Very simple Java Dynamic Casting

后端 未结 3 706
慢半拍i
慢半拍i 2021-01-18 16:03

Simple question but I have spent over an hour with this. My code is below. I need to make SomeClass sc dynamic. So you pass the class name as a string in a function and use

3条回答
  •  温柔的废话
    2021-01-18 16:57

    You want to instantiate a class by it's name?

    First of all, you need to make a Class object:

    Class cls = Class.forName(strClassName);
    

    Then instantiate this (note, this can throw various exceptions - access violation, ClassNotFound, no public constructor without arguments etc.)

    Object instance = cls.newInstance();
    

    Then you can cast it:

    return (SomeClass) instance;
    

    Please make sure you understand the differences between:

    1. A class name (approximately a file name)
    2. A class object (essentially a type information)
    3. A class instance (an actual object of this type)

    You can also cast the cls object to have type Class, if you want. It doesn't give you much, though. And you can inline it, to:

    return (SomeClass)(Class.forName(strClassName).newInstance());
    

    Oh, but you can do type checking with the cls object, before instantiating it. So you only instanciate it, if it satisfies your API (implements the interface you want to get).

    EDIT: add further example code, towards reflection.

    For example:

    if (cls.isInstance(request)) {
      // ...
    }
    

    For invoking methods, you either need to know an interface that you can cast to, or use reflection (the getMethod methods of the cls object):

    Method getRequest = cls.getMethod("getRequest");
    getRequest.invoke(request);
    

提交回复
热议问题