【问题标题】:Is there a way to print java class fields by netbeans code templates?有没有办法通过 netbeans 代码模板打印 java 类字段?
【发布时间】:2017-11-27 19:45:34
【问题描述】:

例如类:

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() 生成器

【问题讨论】:

    标签: java netbeans syntax


    【解决方案1】:

    你可以使用:

    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 来使用 encapsulation

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      相关资源
      最近更新 更多