-1

Im using the following code to get data from JPA class

factory = Persistence.createEntityManagerFactory("abc");
        EntityManager entityManager = factory.createEntityManager();

    classList.add("pack.Person");

    for (Object classOjc : classList) {

        String className = classOjc.toString();

        Query query = entityManager.createQuery("SELECT p FROM " + className + " p");

        @SuppressWarnings("rawtypes")
        List resultList = query.getResultList();

        System.out.println(resultList.size());

        for (Object result : resultList) {

            System.out.println(result.toString());
        }
    }
}



Person [firstName=firstName 1, lastName=lastName 1, bigDecimal=0, myDate=Wed Sep 16 06:42:18 IST 1998], 
Person [firstName=firstName 2, lastName=lastName 2, bigDecimal=0, myDate=Sun May 19 13:12:51 IDT 1957], 
Person [firstName=firstName 3, lastName=lastName 3, bigDecimal=0, myDate=Fri Jun 03 05:09:20 IDT 1949],

the class is

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)

    private String firstName;
    private String lastName;

@Override
public String toString() {
    return "Person [firstName=" + firstName + ", lastName=" + lastName + 
             "]";


....

my question is assume that the override result is like following (give all the attribute and class name), there is a way

Since I override the toString() of the person class the print is like follows but my question is there is a way to print for example just the field names or just the values(assume that I cannot change the to string and it should be the same for every class) the problem is that i can get any class so I can cast the result to person for instance

4

2 回答 2

1

您可以在不知道其类型的情况下反思toString给定。Class

只需遍历它声明的字段并获取它们的值:

public static String myMagicToString(final Object in) throws IllegalArgumentException, IllegalAccessException {
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(in.getClass().getSimpleName()).
            append(" [");
    for (final Field field : in.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        stringBuilder.append(field.getName()).
                append("=").
                append(field.get(in)).
                append(",");
    }
    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
    stringBuilder.append("]");
    return stringBuilder.toString();
}

此示例打印的格式与您描述的相同,但您只需要修改字符串连接即可轻松更改格式。

于 2013-06-01T15:54:42.160 回答
1

为什么不根据需要添加多个 toString 方法。或者编写一个带有要打印的属性列表的方法。

于 2013-06-01T15:52:36.337 回答