Last active
November 3, 2016 01:38
-
-
Save ResolveWang/325d56b33c05dcfc8d6f2747a68540ba to your computer and use it in GitHub Desktop.
Java中利用反射来显示对象所有属性和值
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cn.resolvewang; | |
import com.sun.deploy.util.ArrayUtil; | |
import java.lang.reflect.AccessibleObject; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Modifier; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* JDK1.8 | |
* Created by Administrator on 2016/10/20. | |
* Used to display all fields and values of a non-iterable object and not including its super metas | |
*/ | |
public class ObjectToString { | |
public static String ToString(Object obj){ | |
if (obj == null){ | |
return ""; | |
} | |
List<String> fieldValueList = new ArrayList<>(); | |
Class cls = obj.getClass(); | |
Field[] fields = cls.getDeclaredFields(); | |
AccessibleObject.setAccessible(fields, true); | |
for(Field field:fields){ | |
String temp = field.getName() + "=" ; | |
try{ | |
Object val = field.get(obj); | |
temp += val.toString(); | |
fieldValueList.add(temp); | |
}catch (Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
return String.join(",", fieldValueList); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment