Freewind
Freewind

Reputation: 198218

Simulate `property` in Java: how to use public field as property?

In playframework, it uses javassist library to let the public fields of a class can be used as property.

See the example:

public class User {
    public String name;
}

User user = new User();
user.name = "Freewind"
System.out.println(user.name);

In compilation time, play enhanced the bytecode with javassist, the final code is similar to:

public class User {
    private String name;
    public String getName() { return this.name; };
    public void setName() { this.name = name; };
}

User user = new User();
user.setName("Freewind");
System.out.println(user.getName());

You can see not only the field name has getter and setter, but also the invocations of it changed to getters and setters.

I wonder if there is any other way to do the same (use other things than javassist)?

I found Annotation Processing Tool, but I'm not sure it can do it.

Or aspectj? Or something else?

Upvotes: 0

Views: 241

Answers (2)

Mark Rotteveel
Mark Rotteveel

Reputation: 108992

You can look at Project Lombok, which does something similar, but with annotations. With project lombok you do need to use the getters and setters in your own code.

Upvotes: 1

SLaks
SLaks

Reputation: 887405

Not without other tools.

Unlike C#, Java does not support properties.

Upvotes: 0

Related Questions