十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
import?java.lang.reflect.Field;
創(chuàng)新互聯(lián)建站是專業(yè)的大悟網(wǎng)站建設(shè)公司,大悟接單;提供網(wǎng)站設(shè)計、成都做網(wǎng)站,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行大悟網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
/**
*?簡單反射
*
*?@author?huanghuapeng?2017年3月21日
*?@see
*?@since?1.0
*/
public?class?CountLine?{
public?static?void?main(String[]?args)?{
Person?person?=?new?Person();
Class??extends?Person?clazz?=?person.getClass();
Field[]?fields?=?clazz.getDeclaredFields();
for?(Field?field?:?fields)?{
Class??type?=?field.getType();
System.out.println(type);
}
}
}
class?Person?{
private?int?id;
private?String?name;
public?int?getId()?{
return?id;
}
public?void?setId(int?id)?{
this.id?=?id;
}
public?String?getName()?{
return?name;
}
public?void?setName(String?name)?{
this.name?=?name;
}
}
Class??cls=Class.forName(className);//通過類的名稱反射類
Object?obj=cls.newInstance();//對象實例化
Field?field=cls.getField(fieldName);//這個對應(yīng)的是屬性
fieldValue=field.get(obj);//這個就是屬性的值
/**
* 根據(jù)實例化對象獲取對象的全部屬性
* @param obj 實例化對象
* @return 全部屬性
* @throws Exception
*/
public static String[] getFileNameFromObj(Object obj) throws Exception{
if (obj == null) {
return null;
}
Field[] fields = obj.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
}
注意:前提是對象可以實例化。
先獲取Method對象
以下僅供參考
package?com.kidd.test.zhidao;
import?java.lang.reflect.Method;
/**
*?Hello?world!
*
*/
public?class?Main?{
public?static?void?main(String[]?args)?{
Method?method1?=?null;
Method?method2?=?null;
try?{
method1?=?Class.forName("com.kidd.test.zhidao.Cat").getMethod("getName",?(Class?[])?null);
method2?=?Class.forName("com.kidd.test.zhidao.Cat").getMethod("getChilds",?(Class?[])?null);
}?catch?(NoSuchMethodException?ex)?{
ex.printStackTrace();
}?catch?(SecurityException?ex)?{
ex.printStackTrace();
}?catch?(ClassNotFoundException?ex)?{
ex.printStackTrace();
}
if?(null?!=?method1)?{
System.out.println(method1.getGenericReturnType().getTypeName());
}
if?(null?!=?method2)?{
System.out.println(method2.getGenericReturnType().getTypeName());
}
}
}
class?Cat?{
private?String?name;
private?Cat[]?childs;
public?String?getName()?{
return?name;
}
public?void?setName(String?name)?{
this.name?=?name;
}
public?Cat[]?getChilds()?{
return?childs;
}
public?void?setChilds(Cat[]?childs)?{
this.childs?=?childs;
}
}
Java.lang.Class
getDeclaredFields()
返回 Field 對象的一個數(shù)組,這些對象反映此 Class
對象所表示的類或接口所聲明的所有字段。
Java.lang.reflect.Field
getName()
返回此 Field 對象表示的字段的名稱。
getGenericType()
返回一個 Type 對象,它表示此 Field 對象所表示字段的聲明類型。
以上是jdk里面的一些用法,就是用你想要獲取對象的屬性得到它的class 然后調(diào)用 getDeclaredFields()就可以得到字段數(shù)組了。
然后再用下面的方法就可以得到屬性名,類型這一些。
很簡單,要想實現(xiàn)現(xiàn)復(fù)雜的功能就再找一下api 找出相應(yīng)的方法。