0

I have a XML file :-

<?xml version="1.0"?>
<parameters>
    <benchmarkClass>SmallApp</benchmarkClass>
    <scalefactor>1</scalefactor>
    <terminals>1</terminals>

    <!-- Connection details -->
    <type>POSTGRES</type>
    <driver>org.postgresql.Driver</driver>
    <url>jdbc:postgresql://localhost:5433</url>
    <username></username>
    <password></password>
    <isolation>TRANSACTION_SERIALIZABLE</isolation>
    <batchsize>128</batchsize>
</parameters>

I am using jdom to parse this in Java:-


Document document = saxBuilder.build(path_to_xmlFile);
Element rootElement=document.getRootElement();
Element parameter= (Element) rootElement.getChildren("parameters");
String ImplemenationClass=  parameter.getChildText("benchmarkClass");

I now want to create an object of name Implementation class. For eg:- If the string I get is "SmallApp"

I want to be able to make this call :-

SmallApp ob=new SmallApp();

How to do this? I am new to Java so please be kind!

lets_code
  • 23
  • 6

1 Answers1

0

You need to make use of the Reflection API. So your code might look like:

String implemenationClass="SmallApp";
Class clazz = Class.forName(implemenationClass);
Object instance = clazz.getDeclaredConstructor().newInstance();
// instance now holds a reference to an instance of SmallApp

You want to have the fully qualified class name in your string before instantiating the class. So think about the package.

Queeg
  • 7,748
  • 1
  • 16
  • 42