Capability to instantiate an object based on the String class name (#1074)

It is usefull when you want to set the MetricsTackerFactory from a
property.
pull/1218/head
fpirson 7 years ago committed by Brett Wooldridge
parent 471e27ece0
commit 5d1ed1c678

@ -146,7 +146,14 @@ public final class PropertyElf
writeMethod.invoke(target, propValue.toString());
}
else {
writeMethod.invoke(target, propValue);
try {
LOGGER.debug("Try to create a new instance of \"{}\"", propValue.toString());
writeMethod.invoke(target, Class.forName(propValue.toString()).newInstance());
}
catch (InstantiationException | ClassNotFoundException e) {
LOGGER.debug("Class \"{}\" not found or could not instantiate it (Default constructor)", propValue.toString());
writeMethod.invoke(target, propValue);
}
}
}
catch (Exception e) {

@ -0,0 +1,27 @@
package com.zaxxer.hikari.mocks;
public class TestObject
{
private TestObject testObject;
private String string;
public void setTestObject(TestObject testObject)
{
this.testObject = testObject;
}
public void setString(String string)
{
this.string = string;
}
public TestObject getTestObject()
{
return testObject;
}
public String getString()
{
return string;
}
}

@ -0,0 +1,43 @@
package com.zaxxer.hikari.util;
import org.junit.Assert;
import org.junit.Test;
import com.zaxxer.hikari.mocks.TestObject;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;
public class PropertyElfTest
{
@Test
public void setTargetFromProperties() throws Exception
{
Properties properties = new Properties();
properties.setProperty("string", "aString");
properties.setProperty("testObject", "com.zaxxer.hikari.mocks.TestObject");
TestObject testObject = new TestObject();
PropertyElf.setTargetFromProperties(testObject, properties);
assertEquals("aString", testObject.getString());
assertEquals(com.zaxxer.hikari.mocks.TestObject.class, testObject.getTestObject().getClass());
assertNotSame(testObject, testObject.getTestObject());
}
@Test
public void setTargetFromPropertiesNotAClass() throws Exception
{
Properties properties = new Properties();
properties.setProperty("string", "aString");
properties.setProperty("testObject", "it is not a class");
TestObject testObject = new TestObject();
try {
PropertyElf.setTargetFromProperties(testObject, properties);
fail("Could never come here");
}
catch (RuntimeException e) {
assertEquals("argument type mismatch", e.getCause().getMessage());
}
}
}
Loading…
Cancel
Save