java中的反射

package com.sujianbo.test;

 

public class Person {

 

public static final String motherLand = "china";

 

private String name;

private String sex;

private int height;

 

public Person(){

 

}

 

public Person(String name,String sex,int height){

this.name = name;

this.sex = sex;

this.height = height;

}

 

 

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public int getHeight() {

return height;

}

public void setHeight(int height) {

this.height = height;

}

 

 

 

 

}

 

 

 

 

package com.sujianbo.refletct;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.lang.reflect.Modifier;

import java.lang.reflect.Parameter;

import com.sujianbo.test.Person;

 

@SuppressWarnings("all")

public class Test {

 

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{

 

Class clazz = Class.forName("com.sujianbo.test.Person");

 

Field[] fs = clazz.getFields();

 

for(int i=0;i<fs.length;i++){

int mo = fs[i].getModifiers();

 

System.out.println(Modifier.toString(mo) + " " + fs[i].getName());

 

}

 

System.out.println("============所有的属性============");

 

Field[] fds = clazz.getDeclaredFields();

 

for(int i=0;i<fds.length;i++){

 

int mo = fds[i].getModifiers();

 

System.out.println(Modifier.toString(mo) + " " + fds[i].getName());

 

}

 

System.out.println("============所有的 public 的方法============");

 

Method[]  ms = clazz.getMethods();

 

for(int i=0;i<ms.length;i++){

 

int mo = ms[i].getModifiers();

 

System.out.print(Modifier.toString(mo) + " " + ms[i].getReturnType().getName() + " " + ms[i].getName() + "(");

Parameter[] ps = ms[i].getParameters();

for(int j=0;j<ps.length;j++){

 

System.out.print(ps[j].getParameterizedType().getTypeName() + " " + ps[j].getName());

 

if(j<ps.length){

System.out.print(",");

}

 

 

}

System.out.print(")");

System.out.println();

 

 

}

 

System.out.println("============生成对象 调用对应的方法============");

 

Object obj = clazz.newInstance();

 

 

Method m = clazz.getMethod("setName", Class.forName("java.lang.String"));

 

 

m.invoke(obj, "wangwenming");

 

Person p = (Person)obj;

 

 

System.out.println(p.getName());

 

 

}

 

}

 

posted @ 2016-10-13 16:07  sujianbo  阅读(143)  评论(0编辑  收藏  举报