1

I have data type which contains 100 properties and 100 getter methods (getproperty1....getproperty100).

I get an input from the user like

Property1
Property2
.
.
Property100

How can I invoke in a quick way the method in this logic

For property1 I need to invoke getproperty1
For propertyI I need to invoke getpropertyI

How can I do this with out using if else, or switch statement or reflection in an efficient way.

Thanks

1
  • To how many data bundles are you applying a given list of properties? Commented Nov 15, 2011 at 21:00

3 Answers 3

2

Your best bet is probably going to be an array or hashmap of some type, and access it by index/key:

public class DataType {
    private Map<String, DataProperty> data = new HashMap<String, DataProperty>();

    public DataProperty getProperty(String key) {
        return data.get(key);
    }

    public void setProperty(String key, DataProperty value) {
        data.put(key, value);
    }
}

Although, 100 properties seems like a lot... see if you should break it up or otherwise re-organize it.

Sign up to request clarification or add additional context in comments.

Comments

1

You could refactor the class to be a Map. If you have a large number of objects like that it seems more along the lines of a map than an object.

Map<String, Object>

Comments

1

1. If you need to invoke multiple methods I would suggest using the Strategy design pattern. In it's simplest form you could try

public interface Command<T> {
    public T getProperty();
}

and then create as many implementations as necessary.

2. If you are only interested in the return type and not the actual invokation the Map<String, T> would be a better alternative.

3. If you want to pass around the information in your program a good alternative would be to use the enum approach

public enum Command {
   Property1("some value"),
   Property2("some other value");

   private String str;
   public Command(String str) {
       this.str = str;
   }

   public String getVal() {
       return str;
   }
}

Which can be used like

Command cmd = ...
String value = cmd.getVal();

3 Comments

How can strategy design pattern solve my problem ,it kinds of defining different implementation for abstract class.
@Blue Label, exactly, you declare interface Foo { getProperty(); } and supply one implementation for each property type. Although if you only need the return value the Map approach offered already would be better suited, or alternatively an enum approach.
Thanks but with enum approach I need to use switch statement and do it 100 times is that correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.