Abgebaumt Abgebaumt - 1 year ago 88
Java Question

java.lang.reflect.field getText when field is JTextfield

I have this code:

Field[] fields = getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("_") == true) {
// .getText();

It returns all vars in the Class.

Now I have to .getText() when the var contains a
(Every JTextField var contains a
in name) any Ideas??

Thanks for help.

Answer Source

You can use reflection to figure the actual type of your fields, like:

Field[] fields = getClass().getDeclaredFields();       
for (Field field : fields) {  
    Class<?> fieldType = field.getType();
    if (fieldType.isAssignableFrom(JTextfield.class)) {
      JTextField jtf = (JTextField) field.get(owningobject);       

In other words:

  1. You can check if the field "is" a JTextField (that is much better than relying on some convention that anything with "_" in its name is a textfield)
  2. If so, you simply get the value of the field, and cast it to its real type ... and then, you got a JTextField object, and you can call the method of that class directly!

Please note: my code is meant to get you going - I didn't run it through the compiler or tested it. So, beware of typos. But it should be enough to make your own experiments and help you making progress.

EDIT, regarding your question: all those reflection get/set methods require you some object to work on. Meaning: you need an instance of that class that you are "reflecting" on (unless you are talking about static fields). See here or there for further reading.

A final word of warning; as there are two things you should know when using reflection:

  1. Only use it when there is no other way to solve your problem. Never use it because it seems convenient, but because there is no other way to get what you need!
  2. Only use it when you understand 100% of reflection. Thing is: it is super easy to get reflection wrong. And you only notice at runtime. You can easily spend hours writing reflection code and trying to get it to work; running from one subtle problem into the next one. Getting reflection code is hard. And more painful: a subtle change in the code that "is reflected" can break your reflection-using code; and you don't notice until running that code!

So, long story short, and given your question: you seem to not know much about reflection. In that sense: be really careful. And maybe re-think if there are other, non-reflecting ways to solve your problem!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download