Java 反射 之 访问属性
http://www.verejava.com/?id=16995088370834
package com.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.TypeVariable;
import com.entity.Course;
public class TestField
{
/**
*
* @param args
*/
public static void testGetDeclaredFields()
{
try
{
Class c=Class.forName("com.entity.Student");
Field[] fields=c.getDeclaredFields();
for(Field field:fields)
{
System.out.println(field.getName());
System.out.println(field.getModifiers());
if(field.getModifiers()==Modifier.PRIVATE)
{
System.out.println("private");
}
}
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static void testField()
{
try
{
Class c=Class.forName("com.entity.Student");
Object obj=c.newInstance();
Field field=c.getDeclaredField("money");
//强制访问
field.setAccessible(true);
field.setInt(obj, 1000);
System.out.println(field.getInt(obj));
field=c.getDeclaredField("address");
field.setAccessible(true);
field.set(obj, "北京");
System.out.println(field.get(obj));
field=c.getDeclaredField("course");
field.setAccessible(true);
field.set(obj, new Course("里哈",90));
Course course=(Course)field.get(obj);
System.out.println(course.getName()+","+course.getScore());
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void testType()
{
try
{
Class c=Class.forName("com.entity.Student");
Object obj=c.newInstance();
Field field=c.getDeclaredField("name");
System.out.println(field.getType());
System.out.println(field.getType().getSimpleName());
if("java.lang.String".equals(field.getType().getName()))
{
System.out.println(true);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
testGetDeclaredFields();
}
}
package com.entity;
public class Course
{
private int id;
private String name;
private int score;
public Course()
{
super();
}
public Course(String name, int score)
{
super();
this.name = name;
this.score = score;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}
package com.entity;
public class Student
{
private String name;
private int age;
private int money;
private String address;
private Course course;
public Student()
{
super();
System.out.println("student");
}
public Student(String name, int age)
{
super();
this.name = name;
this.age = age;
System.out.println(this.name+","+this.age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
private String getHello()
{
return "hello";
}
}
student2.xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
<student>
<name>李军</name>
<age>29</age>
</student>
<student>
<name>李浩</name>
<age>21</age>
</student>
</data>