Pergunta

I'm pretty sure this is impossible (considering it is such abysmal programming practice), but I'm going to ask anyway.

In Java, is there a way to use a string in place of a method name (or something else) using the dot operator?

For example: java.stringname.NumericShaper(); where stringname = "awt.font"

I'm trying to put some repetitive code into an iterative loop. For example, one of my variables is "Settings.can1.baud", and I want to iterate the "can1" part each time I go through the loop. Perhaps there's a better way to do this?

I'm new to Java programming, so I'm not sure that made any sense...

Foi útil?

Solução

If you mean you have a bunch of members called can1, can2, can3, etc., then you should use an array or a collection instead.

It is possible to do what you want using reflection. But it's fiddly, bad practice (often), and unnecessary in this case.

Outras dicas

You could do this using reflection:

try {   

        //loop over stringnames?
        String stringname = "awt.font";
        Class<?> numericShaperClass = Class.forName("java." + stringname + ".NumericShaper");


        NumericShaper numericShaper = (NumericShaper) numericShaperClass.newInstance();

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

As for the second part of your question, you can access the member variables of your Properties class using the Class.getField() method.

Using reflection might be overkill in this situation and can result in some pretty unreadable, and possibly slow code.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top