Adding classes to software at runtime

3

Question

  

Is there a feature that some language makes available to be able to add a class to the running software, that is, the software to be recognized in order to instantiate objects of this class and manipulate them?


Let's imagine the following situation:
Take the Java language with example. We have this abstract class made available as a skeleton so that users can implement:

public abstract class TypeGeneral {

    MyAttribute my_atr;   // um objeto qualquer que toda implementação
                          // de TypeGeneral tem que ter
    public General(MyAttribute e) {
         my_atr = e;
    }

    public abstract void run();    // <==

    public MyAttribute getAttr() { /*...*/ }
    public MyAttribute setAttr(MyAttribute e) { /*...*/ }

    // ...
}

I wanted to know if there is a resource that gives the possibility that, after the user has made their class extending TypeGeneral , and thus implementing the run() method, can at runtime add it to the system which is running, and the system, recognizing it, makes manipulations with its objects.

I saw something about Reflection , but I could not adapt to my problem. Anyone willing?

Preferred languages

  • Java
  • Python
  • C#
  • C++
asked by anonymous 15.07.2016 / 19:46

1 answer

0

This is very common in Java. JDBC drivers, for example, are loaded into memory through this kind of mechanism. This is useful in situations where a priori (at development time) can not know the class to be instantiated.

A small example. Suppose the following class exists on your system:

package com.company;

class TesteClasseDinamica {
    public int x;
    public int y;
}

Suppose now that you are in another class and want to instantiate an object of class com.company.TesteClasseDinamica dynamically:

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    Class clazz = Class.forName("com.company.TesteClasseDinamica");

    TesteClasseDinamica t = (TesteClasseDinamica) clazz.newInstance();
    t.x = 2;
    t.y = 3;

    System.out.print(t.x);
    System.out.print(t.y);
}

Note that in this scenario, to instantiate an object of class TesteClasseDinamica , the method newInstance() of class Class is used.

This is very important in JDBC, since the interface must be generic in order to serve any relational database. Since it is not possible to predict the implementation (JDBC driver) used by the application, this mechanism is used to dynamically instantiate the driver.

    
19.07.2016 / 19:51