Die einfache Art Java Code dynamisch auszuführen... ;-)

Thomas Darimont

Erfahrenes Mitglied
Hallo!

Code:
/*
 * Created on 28.12.2004@22:57:48
 *
 * TODO Licence info
 */
package de.tutorials;

import java.beans.Statement;

/**
 * @author Administrator
 * 
 * TODO Explain what I do...
 */
public class DynamicCodeExample {
	public static void main(String[] args) {
		Statement exp = new Statement(System.out, "println",
				new Object[] { "tutorials.de -user helfen usern-" });
		try {
			exp.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Gruß Tom
 
Was hast Du nur gegen die gulte alte Reflection? :eek:

Code:
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
  
  public class Test{
  	public static void main( String...args ) throws Exception{
  		Class system = Class.forName( "java.lang.System" );
  		Field out = system.getField( "out" );
  		Class stream = out.getType();
 		Method println = stream.getMethod( "println", new Class[]{ Class.forName( "java.lang.String" ) } );
  		println.invoke( out.get( null ), new Object[]{ "Hello World" } );
  	}
  }
 
Hallo!

Ich finde die erstere Methode leichter und vor allem weniger "geschwätzig" als bei reflection... ;-)
Code:
/*
 * Created on 28.12.2004@22:57:48
 *
 * TODO Licence info
 */
package de.tutorials;

import java.beans.Statement;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Administrator
 * 
 * TODO Explain what I do...
 */
public class DynamicCodeExample {
	public static void main(String[] args) {
		Statement exp = new Statement(System.out, "println",
				new Object[] { "tutorials.de -user helfen usern-" });
		try {
			exp.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Method m;
		try {
			m = System.out.getClass().getMethod("println",
					new Class[] { String.class });
			Object ret = m.invoke(System.out,
					new Object[] { "tutorials.de -user helfen usern-" });
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Gruß Tom
 
Zurück