Java:获取类的属性来构造字符串表示 [英] Java: Getting the properties of a class to construct a string representation

查看:267
本文介绍了Java:获取类的属性来构造字符串表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的类(并且还假设所有的私有变量:

  public class Item { 
private String _id = null;
private String _name = null;
private String _description = null;

...
}

现在,如果我想构建一个toString class:

  @Override 
public String toString(){
return(_id ++ _name ++ _description);
}

但是如果我说15个私有变量在类中?我必须写这样的每个变量的名称吗?



理想情况下,我想通过迭代列表来完成任务的私有变量并构造字符串表示形式:

  @Override 
public String toString(){
ArrayList< String> members = getClass()。getMembers(); //像这样的一些方法
String string =;
for(...)
string + = members [i] +;
}

或者一个toJSON方法,我仍然需要访问这些变量。任何建议?

解决方案

您可以:

  @Override 
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(getClass()。getName());
sb.append(:);
for(Field f:getClass()。getDeclaredFields()){
sb.append(f.getName());
sb.append(=);
sb.append(f.get(this));
sb.append(,);
}
return sb.toString();
}

不要使用字符串连接构造最终结果来自15个数据成员,特别是如果 toString()将被调用很多。内存碎片和开销可能真的很高。使用 StringBuilder 构建大型动态字符串。



我通常得到我的IDE(IntelliJ) $ c> toString()方法,而不是使用反射为此。



另一个有趣的方法是使用来自Project Lombok的@ ToString注释


  import lombok.ToString; 

@ToString(excludes =id)
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private形状shape = new Square(5,10);
private String [] tags;
private int id;

@ToString(callSuper = true,includeFieldNames = true)
public static class Square extends {
private final int width,height;

public Square(int width,int height){
this.width = width;
this.height = height;
}
}
}


我发现这更好一些,比如说,Jakarta Commons toString构建器,因为这种方法是更可配置的,它也是在编译时构建而不是运行时。


Let's say I have a class like this (and also further assume that all the private variables:

public class Item {
    private String _id = null;
    private String _name = null;
    private String _description = null;

        ...
}

Now, if I want to build a toString() representation of this class, I would do something like this inside the Item class:

@Override
public String toString() {
    return (_id + " " + _name + " " + _description);
}

But what if I have say 15 private variables inside the class? Do I have to write the name of each and every variable like this?

Ideally, I would like to get over with the task by iterating through the list of private variables of this class and construct the string representation:

@Override
public String toString() {
    ArrayList<String> members = getClass().getMembers(); //Some method like this
    String string = "";
    for(...)
        string += members[i] + " ";
}

Or perhaps a toJSON method, I would still need access to the names of these variables. Any suggestions?

解决方案

You could do:

@Override
public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(getClass().getName());
  sb.append(": ");
  for (Field f : getClass().getDeclaredFields()) {
    sb.append(f.getName());
    sb.append("=");
    sb.append(f.get(this));
    sb.append(", ");
  }
  return sb.toString();
}

Don't use string concatenation to construct an end result from 15 data members, particularly if the toString() will be called a lot. The memory fragmentation and overhead could be really high. Use StringBuilder for constructing large dynamic strings.

I usually get my IDE (IntelliJ) to simply generate toString() methods for me rather than using reflection for this.

Another interesting approach is to use the @ToString annotation from Project Lombok:

import lombok.ToString;

@ToString(excludes="id")
public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;

  @ToString(callSuper=true, includeFieldNames=true)
  public static class Square extends Shape {
    private final int width, height;

    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
  }
}

I find this much more preferable to, say, Jakarta Commons toString builders because this approach is far more configurable and it's also built at compile-time not run-time.

这篇关于Java:获取类的属性来构造字符串表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆