-1

Sometimes when i have some object with lots of attributes (for example 30-40) it is really anoying to write getter and setter methods so in javascript i do something like this:

function SomeObject( properties ) 
{ 
   // Iterate through the properties of the object, and make sure 
   // that it's properly scoped.
   for ( var i in properties ) 
   { 
       (function(){ 
        // Create a new getter for the property 
        this[ "get" + i ] = function() 
        { 
           return properties[i]; 
        };
        // Create a new setter for the property 
        this[ "set" + i ] = function(val) 
        { 
           properties[i] = val; 
        }; 
    })(); }
 }

So i am just wondering if it is possible to do something like this in JAVA?

4

5 回答 5

3

Code-generating annotations can do this sort of thing in Java. You might want to take a look at Project Lombok.

Related, I think: Using Java Annotations - Generating Code

于 2013-07-11T09:49:19.320 回答
1

In Eclipse:

Rightclick -> Source -> Generate Getters and Setters

There are also other nice generators, for example, for constructors, hashCode/Equals.

All common IDEs have such a functionality, which saves alot of time.

于 2013-07-11T09:50:03.050 回答
1

Suppose if i give you a class with 30-40 getters/setters. How would you feel while using. I don't think its a good idea to have 30-40 getter/setters in a single class. Rather you break/distribute class by subclassing properties

The example you gave from javascript is avery good example. On how we should access if we so many properties in a single class. In javascript you can tread a object like a Map.

I would apply the same idea if i have the requirement of 30/40 getter setters.

i.e Either i would use java.util.Properties

or made My Custom Class

  //Only if you have 30/40 properties
  class MyClass {

       private Map<String, Object> data = new ConcurrentHashMap<String,Object>();

       public void set(String fieldName, Object value) {
               data.put(fieldName, value);
       }

       public Object get(String fieldName) {
               return data.get(fieldName);
       }

   }
于 2013-07-11T10:52:38.260 回答
0

In Eclipse you can use the function "Source > Getter and Setter" and automatically will be added in your code all the setter and getter that you want!

于 2013-07-11T09:48:58.720 回答
0

Maybe try ascepects and Spring Roo like :

@RooJavaBean
public calss SimpleClass {
    private Attr1 attr1;
    private Attr2 attr2;

} 

Tutor

于 2013-07-11T09:57:43.080 回答