dynamic programming

Status
Nicht offen für weitere Antworten.
J

javaprog

Gast
Hi Community,

is there a way to do a dynamic programming.
Example:

String str="int";
str x=4; //x is int

I know in php is a solution to do this.
Is this in java possible?

Many thanks

Olaf
 

Mag1c

Top Contributor
Hi,

nein, sowas geht nicht direkt. Man kann mit Reflection sehr viel machen:

Code:
String str = "java.lang.Integer";
Class cls = Class.forName(str);
Constructor con = cls.getConstructor(new Class[] {Integer.TYPE});
Object x = con.newInstance(new Object[] {new Integer(4)});

aber du siehst schon an dem simplen Beispiel, daß das nichts fürs Alltägliche ist ;)

Gruß
Mag1c
 

Bleiglanz

Gesperrter Benutzer
yes and no

even in php this can fail for various reasons...
Code:
    public static void main(String[] args){
        Object o = create("java.lang.Integer",42);
        System.out.println(o);
    }
    public static Object create(String name, Object value){
        Object result = null;
        try {
            Class clazz = Class.forName(name);
            Constructor constructor = clazz.getConstructors()[0];
            result = constructor.newInstance(new Object[]{value});
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }
 

m@nu

Bekanntes Mitglied
if you're intressted in this subject, search the web for "reflection" ... the framework which provides these functionalities is called like this.
as i know, they had some performance problems in older JVM versions... but i guess it should be better today
 
Status
Nicht offen für weitere Antworten.

Ähnliche Java Themen

Neue Themen


Oben