Skip to content

Instantly share code, notes, and snippets.

@hseritt
Created June 27, 2016 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hseritt/f8a4cc43df13f7cba50275331e37aaa3 to your computer and use it in GitHub Desktop.
Save hseritt/f8a4cc43df13f7cba50275331e37aaa3 to your computer and use it in GitHub Desktop.
Dynamic class instantiation using Thread
public class Controller implements Runnable {
private static Logger logger = Logger.getLogger(Controller.class);
public void run() {
logger.info("Starting subsystem AgentController");
String sql = "select * from agent where active=true";
DbConnector db = new DbConnector();
ResultSet agentList = null;
try {
agentList = db.query(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
while (agentList.next()) {
logger.info("Starting agent '" + agentList.getString("name") + "'");
logger.info("Using class name: " + agentList.getString("class_name"));
BaseAgent agent = (BaseAgent) Class.forName(agentList.getString("class_name")).newInstance();
Thread agentThread = new Thread(agent);
agentThread.start();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("Closing database connection");
try {
db.close();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Agent controller finished.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment