![](/img/trans.png)
[英]what is the best way to print all the values of the fields in a java class
[英]Is there a way to print java class fields by netbeans code templates?
例如类:
public class JavaClassExample{
private String field_1;
public String field_2;
public int field_3;
}
要获得的代码模板:
System.out.println(field_1 + " " + field_2 + " " + field_3);
我也可以用它来创建自己的toString()生成器
您可以使用:
class Main {
public static void main(String[] args) {
JavaClassExample c = new JavaClassExample();//create an instance of your class
System.out.println(c.field_2 + " " + c.field_2
+ " " + c.field_3);//call the fields
}
}
您还可以使用使用getter和setter的封装 :
System.out.println(c.getField_1() + " " + c.getField_2() + " " + c.getField_3());
或者您可以使用toString
:
public class JavaClassExample {
private String field_1;
private String field_2;
private int field_3;
//...getters and setters
@Override
public String toString() {
return field_2 + " " + field_2 + " " + field_3;
}
}
因此,您可以仅使用以下命令打印对象:
System.out.println(c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.