java 属性 标示,Java:获取类的属性来构造字符串表示

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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值