Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

后端 未结 6 1264
忘掉有多难
忘掉有多难 2020-12-03 03:30

All the examples I look at for reflection show creating a new instance of an unknown implementation, and casting that implementation to it\'s interface. The issue with this

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 03:49

    I'm not absolutely sure I got your question correctly, but it seems you want something like this:

        Class c = null;
        try {
            c = Class.forName("com.path.to.ImplementationType");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        T interfaceType = null;
        try {
            interfaceType = (T) c.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    

    Where T can be defined in method level or in class level, i.e.

提交回复
热议问题