groovy调用java接口,我可以使用groovy的默认getter / setter来帮助实现一个java接口吗?...

I am extending a very simple Java interface from an imported library. The interface is so simple that the only methods it declares are getters and setters for a list of properties.

My application is written in Groovy, so I'd like to implement this Java interface with a Groovy class.

I was under the impression that Groovy created getters and setters by default for any of its classes' properties - can I use these default getters and setters to satisfy the Java interface's requirements?

Library's Java interface:

public interface Animal { // java interface

public String getName();

public void setName(String name);

public Integer getAge();

public void setAge(Integer age);

}

I hoped I'd be able to implement it like this with Groovy (but my compiler is complaining about missing setters):

public class Cat implements Animal { // Groovy class

public String name;

public Integer age;

}

解决方案

You can do that with groovy properties, but take into account the difference between

A field is a member of a class or a trait which:

a mandatory access modifier (public, protected, or private)

one or more optional modifiers (static, final, synchronized)

an optional type

a mandatory name

[...]

A property is a combination of a private field and getters/setters.

You can define a property with:

an absent access modifier (no public, protected or final)

one or more optional modifiers (static, final, synchronized)

an optional type

a mandatory name

Groovy will then generate the getters/setters appropriately.

When you put an explicit access modifier, you are actually using a field, so getters/setters are not generated and that's why the compiler complains about Can't have an abstract method in a non-abstract class, since getters/setters are not there.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值