开发者

Runtime Casting of the Type Object

开发者 https://www.devze.com 2023-03-23 23:12 出处:网络
I\'d like to instantiate an object of a generic class during run-time; I call a method which gives me back a Type Object; I\'d like to convert this generic class into a specific class, and then instan

I'd like to instantiate an object of a generic class during run-time; I call a method which gives me back a Type Object; I'd like to convert this generic class into a specific class, and then instantiate objects of this class. Is it possible? I used to write in Java:

Class<DBConnectionProvider> dBConnectionProvider开发者_开发问答Class =
              (Class<DBConnectionProvider>)Configuration.getInstance().getDbConnectionProviderClass();

The method getDbConnectionProviderClass() returns a Class Object which is converted on run-time; In my C# application this method returns a Type object; is it possible to convert this in DBConnectionProvider and instantiate a class of this? Thank you for your answers.


Once you have the type object you just need to call:

object o = Activator.CreateInstance([your type]).Unwrap();

or if you need to supply constructor arguments:

object o = Activator.CreateInstance([your type], obj1,obj2...).Unwrap();

And then cast to your type.


Simple example of creating instances of classes with reflection (Java)

import java.awt.Rectangle;

public class SampleNoArg {

   public static void main(String[] args) {
      Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
      System.out.println(r.toString());
   }

   static Object createObject(String className) {
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消