java – Add classes to software at runtime

Question:

Question

Are there any resources that any language makes available to be able to add a class to the running software at runtime, that is, the software to recognize and thus be able to instantiate objects of that class and manipulate them?

Let's imagine the following situation:
Take the Java language as an example. We have this abstract class made available as a skeleton for users to 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 was wondering if there is any feature that gives the possibility that, after the user makes his class by extending the TypeGeneral , and thus implementing the run() method, he can, at runtime, add it to the running system, and the system, recognizing it, makes manipulations with its objects.

I saw something about Reflection , but I couldn't adapt to my problem. Anyone willing?

Preferred languages

  • Java
  • Python
  • C#
  • C++

Answer:

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

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

package com.company;

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

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

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 TesteClasseDinamica class, the method newInstance() of class Class .

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

Scroll to Top