Automatically add private classifier to fields in eclipse

Is there a way to automatically add a private qualifier while new variables are declared in Eclipse?

In a sense, I would like to override the default access to private

+7
java eclipse
source share
2 answers

I do not know how to do that.

However, as I write the code, this is rarely necessary. This is because I rarely define fields manually; instead, I let Eclipse create them, and when it does, it makes them private.

Let's say I want to create a Foo class with one bar field of type int . Start with:

 public class Foo { } 

Place the cursor in the body of the class, press control-space and select "default constructor" from the suggestions menu. Now you have:

 public class Foo { public Foo() { // TODO Auto-generated constructor stub } } 

Delete useful comment. Now manually add the constructor parameter for bar :

 public class Foo { public Foo(int bar) { } } 

Now place the cursor on the bar declaration and press control-1. In the offers menu, select "Assign Parameter to New Field":

 public class Foo { private final int bar; public Foo(int bar) { this.bar = bar; } } 

Bingo. Now you have a personal field.

There is a similar sequence of automatic operations that can create a field from an existing expression in a method (first creating a local variable and then moving it into the field).

+3
source share

If you think this is more important to you than performance and readability, I suppose you could set up a relatively convenient solution as follows. I wouldn’t do it myself.

For class and instance variables, change the template template in the settings to enable this:

 private static Object fields = new Object () { // declare all class variables here }; private Object vars = new Object () { // declare all instance variables here }; 

For local variables, change the method template in the settings to enable this:

 private Object locals = new Object () { // declare all local variables here }; 

A class variable x will be declared in fields . It will be closed in this.class.fields.x .

The instance variable y will be declared in vars . It will be closed at this.vars.y

The local variable z will be declared in locals . It will be closed at locals.z .

If you do this, you can expect your entire program to be slower and use more memory than otherwise.

0
source share

All Articles