我在做什么..
public class Employee {
private int eid;
private String name;
public Employee(int eid, String name) {
this.eid = eid;
this.name = name;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
public class TableName<T> {
public void addTableData(List<T> t) {
if (t.size() > 0) {
Class c = t.get(0).getClass();
Field[] f1 = c.getDeclaredFields();
for (T t1 : t) {
Class<T> tClass = (Class<T>) t1;
for (Field field : f1) {
String name = field.getName();
System.out.println(name);
}
}
}
}
}
import java.util.*;
public class Test {
public static void main(String[] args) {
TableName<Employee> table = new TableName<Employee>();
List<Employee> list = new ArrayList<>();
list.add(new Employee(1, "Pankaj"));
list.add(new Employee(2, "Gupta"));
list.add(new Employee(3, "kumar"));
list.add(new Employee(4, "pintu"));
list.add(new Employee(5, "rinku"));
list.add(new Employee(6, "tinku"));
table.addTableData(list);
}
}
我必须打印像1,pankaj 2 gupta等对象的值或者相应的getter setter。
感谢。
答案 0 :(得分:1)
如果必须使用反射,则应该能够获得如下字段值:
public void addTableData(List<T> list) throws IllegalAccessException {
for (T item : list) {
Class c = item.getClass();
Field[] fields = c.getDeclaredFields();
StringBuilder itemRepr = new StringBuilder();
for (Field field : fields) {
field.setAccessible(true);
String name = field.getName();
Object value = field.get(item);
itemRepr.append(name).append('=').append(value).append(", ");
}
if (itemRepr.length() > 0) {
itemRepr.setLength(itemRepr.length() - 2);
}
System.out.println(c.getSimpleName() + "{" + itemRepr + '}');
}
}
但这种解决方案非常昂贵。为什么不覆盖toString()
类中的Employee
?
class Employee {
// some code here ...
@Override
public String toString() {
return "Employee{name=" + this.name + ", eid=" + this.eid + "}";
}
}
然后使用
打印员工list.forEach(System.out::println);
答案 1 :(得分:0)
你需要覆盖toString()方法并在那里设置必需的字段,并在任何你想打印值的地方调用Object.toString()
答案 2 :(得分:0)
在类中重写toString方法
public class Employee {
private int eid;
private String name;
public Employee(int eid, String name) {
this.eid = eid;
this.name = name;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Assuming only name needs to be printed
public String toString() {
return name;
}
}
你可以像
一样打印出来Employee emp = new Employee(1, "Pankaj")
System.out.println(emp);
希望这有帮助