开发者

Android, avoid typing the object name for each of its properties in a method?

I have an object instance called myClass and i need to set the value of about 30 variables in the object, and I need to do it about 30 times (in 30 methods) in my class.

myClass.vOne
myClass.vTwo
...
myClass.vThirty

Is there some w开发者_开发技巧ay I can save myself from having to type "myClass." 900 times?


If you have 30 variables that need to be set, you have 30 variables that need to be set. You could create some functions that let you set related groups of items in a single call.

public void setStuffAboutThings(int a, int b, int c, int d, int e, int f) {
   vOne = a;
   vTwo = b;
   vThree = c;
   vFour = d;
   vFive = f;
}

...

MyClass.setStuffAboutThings(10, 20, 30, 40, 50);

But really when it comes down to it, if you need to set 30 variables, you have to set 30 variables. You could also type out all the member variables you want to set and then use an editor that supports a column based text editing mode and just insert "MyClass" 30 times at once.

Depending on your data, perhaps you could instead create an array, list, or hash and set the values into it using some kind of loop.

Without knowing more specifics it really isn't possible to guide you.


If I understand correctly, you're looking for a construct similar to VB's With. Java does not have such a construct as it's generally considered a bad practice since it obscures your code solely for the purpose of saving keystrokes.

Two alternatives you can consider:

  1. Record a short macro in your IDE
  2. Prior to doing your mass property operations, you can shorten the name of your object to a single-character name. This does still obscure things, but it comes as close as you can to what you're looking for.


Write a method in your class, which you would call from another places. Something like:

public void init(List<Object> args) {
   vOne = args.get(0);
   vTwo = args.get(1);
   ...
}

and the client code:

List<Object> args = new ArrayList<Object>(30);
args.add(1);
args.add(2);
...
myClass.init(args);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜