Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * WITH THIS CLASS IT'S POSSIBLE TO RUN METHODS AND CONSTRUCTOR IN THREADS
- * + THERE IS A WATCHDOG TO RUN THE METHODS ONLY FOR SOME SECONDS
- */
- package game;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- public class SecureInstance implements Runnable {
- /* Class for ainitialize a new Object via Thread */
- String classname;
- Object returnValue = null;
- Thread t = null;
- public SecureInstance(String a){
- classname = a;
- // Start the Thread for creating an instance of the class
- t = new Thread(this);
- t.start();
- }
- public Object getInstance(){
- try {
- // Wait until the Thread initialize the Object then return..
- t.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return returnValue;
- }
- public void run() {
- // Create The WatchDog with maxtime = 2 seconds
- WatchDog watchdog = new WatchDog(2);
- Thread wdthread = new Thread(watchdog);
- // Add this thread to the WatchDog
- watchdog.addThread(Thread.currentThread());
- wdthread.start();
- try{
- this.returnValue = (Object) Class.forName(classname).newInstance();
- }catch(Exception e){}
- watchdog.close();
- }
- public Object callMethod(String a){
- // If you want to call any method from the Instance
- RunMethod x = new RunMethod(a,this);
- return x.getReturnValue();
- }
- private class RunMethod implements Runnable{
- // Class to run the method
- private String method = null;
- private SecureInstance instance = null;
- private Object returnValue = null;
- private Thread t;
- RunMethod(String a,SecureInstance b){
- this.method = a;
- this.instance = b;
- t = new Thread(this);
- WatchDog wd = new WatchDog(1);
- Thread wdthread = new Thread(wd);
- wd.addThread(t);
- wdthread.start();
- t.start();
- try {
- t.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- }
- wd.close();
- }
- public Object getReturnValue(){
- try {
- // Wait until we have got a value to return
- t.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- }
- return returnValue;
- }
- @Override
- public void run() {
- try {
- // Get the Method and then the return Value
- Method m = instance.getInstance().getClass().getMethod(this.method);
- this.returnValue = (m.invoke(instance.getInstance()));
- } catch (Exception e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement