简体   繁体   English

我们可以在 pojo 中有两个二传手吗?

[英]Can we have two setters in a pojo?

I have a setter that converts a string to byte[] and one simple setter which just sets the value.我有一个将字符串转换为 byte[] 的 setter 和一个只设置值的简单 setter。 My question here is, is it a good practice to have two setters in a POJO?我的问题是,在 POJO 中有两个二传手是一个好习惯吗? I can't find any workaround :(我找不到任何解决方法:(

Example:例子:

byte[] a;

//Case 1: Where we recieve parameter as a string and convert it to byte array and set it to a; 
public void setA(String aString){
this.a=convertTobyteArray(aString);
}

//Case 2: Where we receive parameter as a byte array where conversion is not required and we directly assign it to a
public void setA(byte[] a){
this.a=a;
}

Well, it compiles so literally you can!嗯,它编译得如此真实,你可以! :-) Anyway it's probably not the answer you want to hear. :-) 无论如何,这可能不是您想听到的答案。 From the two methods, only setA(byte[]) is setter in the meaning as was coined by JavaBeans specification.在这两种方法中,只有setA(byte[])是 JavaBeans 规范创造的意义的 setter。 The other method is just helper method with name starting with set .另一种方法只是名称以set开头的辅助方法。 I think your code is ok in most cases.我认为您的代码在大多数情况下都可以。 Some problem could arise if some reflection-based tool scanned the methods (rather than fields because they are public) and tried to guess the field type from method parameter type - it would be confused then.如果某些基于反射的工具扫描方法(而不是字段,因为它们是公共的)并试图从方法参数类型中猜测字段类型,则可能会出现一些问题 - 那样会混淆。

Also I would also consider to reimplement helper method as:此外,我还会考虑将辅助方法重新实现为:

public void setA(String aString){
    setA(convertTobyteArray(aString));
}

A setter is simply a public void method that changes the value of an encapsulated field, and in Java you can add as much methods as you want with the same name and different signatures thanks to method overloading . setter 只是一个更改封装字段值的public void方法,在 Java 中,由于方法重载,您可以添加任意数量的具有相同名称和不同签名的方法

So the answer is YES you can have multiple setters with different parameters and it's not considered a bad practice.所以答案是肯定的,你可以有多个具有不同参数的设置器,这不被认为是一种不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM