当前位置: 首页 > 面试题库 >

Java 打印类中的所有变量值

尉迟国发
2023-03-14
问题内容

我有一堂课,其中包含有关Person的信息,看起来像这样:

public class Contact {
    private String name;
    private String location;
    private String address;
    private String email;
    private String phone;
    private String fax;

    public String toString() {
        // Something here
    }
    // Getters and setters.
}

我想toString()返回this.name +" - "+ this.locations + ...所有变量。我试图使用反射来实现它,如该问题所示,但我无法打印实例变量。

解决此问题的正确方法是什么?


问题答案:

从实现toString:

public String toString() {
  StringBuilder result = new StringBuilder();
  String newLine = System.getProperty("line.separator");

  result.append( this.getClass().getName() );
  result.append( " Object {" );
  result.append(newLine);

  //determine fields declared in this class only (no fields of superclass)
  Field[] fields = this.getClass().getDeclaredFields();

  //print field names paired with their values
  for ( Field field : fields  ) {
    result.append("  ");
    try {
      result.append( field.getName() );
      result.append(": ");
      //requires access to private field:
      result.append( field.get(this) );
    } catch ( IllegalAccessException ex ) {
      System.out.println(ex);
    }
    result.append(newLine);
  }
  result.append("}");

  return result.toString();
}


 类似资料:
  • 我的代码: 我试图像java语法一样打印变量C++,只是作为一个实验。但输出:

  • #include <stdio.h> struct child { char name[10]; enum { boy, girl } gender; }; struct child he = { "Tom", boy }; int main (void) { static struct child she = { "Jerry", girl }; printf ("Hell

  • 如何使像这样打印: 在调试过程中,我曾在许多地方将许多打印语句作为日志编写。我会写这样的声明 我想要一个打印变量名和变量值的方法。在C中,可以按如下方式进行: 有什么办法可以做到这一点吗? 提前感谢。

  • 问题内容: 对于Python中的类,如何定义一个函数以函数中定义的格式打印类的每个实例? 问题答案: 在这种情况下,我看到两个选择: 垃圾收集器 这样做的缺点是,当您有很多对象时,它会非常慢,但会与您无法控制的类型一起使用。 使用mixin和weakrefs 在这种情况下,所有引用都将作为弱引用存储在列表中。如果您经常创建和删除很多实例,则应在迭代后清理弱引用列表,否则会产生很多麻烦。 这种情况下

  • 我有以下几点: 如何打印的类型? 使用和不起作用。还有其他方法可以打印号码的类型吗?

  • 问题内容: 我有一个类,我想找到它的所有 公共字段 (不是方法)。我怎样才能做到这一点? 谢谢! 问题答案: 返回该类的所有公共变量的数组。 返回整个类继承中的字段。如果要仅在相关类中定义字段,而不在其超类中定义字段,请使用,并通过以下方法过滤它们: 的字面实际上代表类型的对象。检查其文档以获取更多有趣的反射方法。 上面的类是。您可以查看整个程序包。