简体   繁体   中英

Runtime Casting of the Type Object

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> dBConnectionProviderClass =
              (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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM