![](/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.