我有一个包含大量字段的类,所有字段都是私有(private)的(子类访问一些 protected getter)。我需要将这些字段中的大部分传递给另一个类中的方法,该方法将格式化它们并生成输出。在类中有一个方法可以传递所有的字段吗?或者这些情况是否表明我应该在这两个类之间实现一些其他关系,因为它们因此看起来紧密耦合?
更多信息:A 类代表 Employees,B 类的唯一职责是格式化程序的输出。
最佳答案
您是在问是否可以执行以下操作?
public class A {
private B myB = new B();
private String myUnformattedName = "some information";
public String getFormattedInfo() {
return myB.formatInfo(myUnformattedName);
}
}
那完全没问题。
Marking a field as private just means that only the containing class should be able to access it...
如果你的意思是别的,最好在你的问题中弹出一些代码来给人们提供上下文
好的,所以无法在此处设置值,但您可以在此处看到调用格式化程序的两种不同方式。当参数列表超过三项或四项时,就会变得难以阅读。
在这种情况下,我只是将 A 传递给格式化程序,并为您希望 B 能够读取的每个值提供一个 get 方法。
public class A {
private B myB = new B();
private String myUnformattedName = "some information";
private String myUnformattedNameOne = "some information";
private String myUnformattedNameTwo = "some information";
private String myUnformattedNameThree = "some information";
private String myUnformattedNameFour = "some information";
private String myUnformattedNameFive = "some information";
private String myUnformattedNameSix = "some information";
public String getFormattedInfo() {
//pass the object itself and use get methods
return myB.formatInfo(this);
}
public String getFormattedInfoLong() {
//this is OK but gets difficult to read the longer the
//parameter list gets
return myB.formatInfo(myUnformattedName, myUnformattedNameOne,
myUnformattedTwo, myUnformattedNameThree, myUnformattedNameFour,
myUnformattedNameFive, myUnformattedNameSix);
}
//getters
public String getUnformattedName() {
return myUnformattedName;
}
public String getUnformattedNameOne() {
return myUnformattedNameOne;
}
//etc
}
关于Java - 有一个方法可以将私有(private)字段值传递给另一个类的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899468/