simranNarula simranNarula - 3 months ago 83
Java Question

Shortcut for calling all the setter methods on an object in Eclipse?

I want to create an object of a class in and then set all the properties in it using setter methods. There are more than 150 setter methods and I do want to type each one of them or even type in the object instance name

Object instance
type in dot
.
and then hit the spacebar for Eclipse to give me suggestions and then go and select the setter method. I do not want to do that 150 times.

Thus, I was looking for some sort of shortcut in Eclipse that allows you to call all the setters on the method. So like you type in the instance name and Eclipse calls all the setter methods e.g.


  • instanceName.setterOne("valOne");

  • instanceName.setterTwo("valOne");

  • instanceName.setterThree("valOne");



I cannot create another constructor in the the class, I am not allowed to do so

Answer

From my experience last time , I cannot find eclipse has such feature .The most that I can do is open the Type Hierarchy View (by pressing F4 when viewing that class ), and then sort by the method name of that class and copy all the setters for further edit.

Or , you can use reflection to find out all the methods of this class , and print out the setter calls , something like this:

         try {
            Class c = Class.forName("your.class.name");
            Method m[] = c.getMethods();
            for (int i = 0; i < m.length; i++)
             if (m[i].getName().startsWith("set")){
                 System.out.println("instanceName."+m[i].getName()+"(\"valOne\");");
             }

         }
         catch (Throwable e) {
            System.err.println(e);
         }