This discussion is archived
13 Replies Latest reply: Feb 6, 2010 7:38 AM by 843798 RSS

Get string value via string doesn't work?

843798 Newbie
Currently Being Moderated
Hello, i'm trying to retrieve a String:

I tried some things, but doesn't work. Current code:
I also don't really get what the Object obj in the method Field.get(Object obj) is.
Can anyone explain this, because this is the probably the error.
public class Run implements Runnable {

public String value = null;
     public static void main(String[] args) {
          Run r = new Run();
          r.value ="should work fine";
          new Thread(r).start();

     }

     @Override
     public void run()
     {
          while(true)
          {
               System.out.println(value);
               try {
                    Thread.sleep(1000);
               } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               }
          }
          
     }

}
import java.lang.reflect.Field;



public class Test2
{
     
     public static void main(String[] args)
     {
          run();
     }
     public static void run()
     {
          Class<?> c = null;
          try {
               c = Class.forName("Run");
          } catch (ClassNotFoundException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
          for(Field f : c.getFields())
          {
               String value = null;
               String v = null;
               f.setAccessible(true);
               System.out.println("Field <+"+f.getName()+"> has the value:");
               try {
                    try {
                         Field z = c.getField(f.getName());
                         value = (String) z.get(new String());
                         //if(value == null) continue;
                    } catch (IllegalArgumentException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                    } catch (IllegalAccessException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                    }
                    System.out.println("-> "+value+" v: "+v);
               } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               } catch (NoSuchFieldException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               }
          }
     }
}