定义一个接口
package cn.yangtao.reflect;
public interface China {
public static final String NATIONAL="China";
public static final String AUTHOR="小明";
public void sayChina();
public String sayHello(String name,int age);
}
定义一个Person类实现以上的接口
package cn.yangtao.reflect;
public class Person implements China {
private String name;
private String age;
public Person(){}
public Person(String name, String age) {
super();
this.name = name;
this.age = age;
}
public Person(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String sayHello(String name, int age) {
// TODO Auto-generated method stub
return name+",你好!我今年"+age+"岁了";
}
public void sayChina() {
// TODO Auto-generated method stub
System.out.println("作者:"+AUTHOR+",国籍"+NATIONAL);
}
}
1、取得Person类所实现的全部接口
package cn.yangtao.reflect;
public class GetInterfaceDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class<?>c1=null;
try {
c1=Class.forName("cn.yangtao.reflect.Person");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Class<?>[]inter=c1.getInterfaces();
for(Class c:inter){
System.out.println(c.getName());
}
}
}
2、取得Person类的全部构造方法
package cn.yangtao.reflect;
import java.lang.reflect.Constructor;
public class GetConstructorDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class<?>c2=null;
try {
c2=Class.forName("cn.yangtao.reflect.Person");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Constructor[] c=c2.getConstructors();
for(Constructor c1:c){
System.out.println(c1.getName());
}
}
}
3、取得单个构造方法
import java.lang.reflect.*;
public class ReflectDemo02{
public static void main(String args[])throws Exception{
Class<String> c1=String.class;
Constructor<String>con=c1.getConstructor(String.class);
String str=con.newInstance("abcd");
System.out.println(str.charAt(2));
}
}
如果不是String 类而是自己定义的类,如Person类,最好可以定义一个无参的构造方法。这样在实例化时不用传入参数
而对于Person类属性的操作可以通过Person类的setter和getter方法
4、取得Person类的父类
package cn.yangtao.reflect;
public class GetSuperDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class<?>c=null;
try {
c=Class.forName("cn.yangtao.reflect.Person");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Class<?>c1=c.getSuperclass();
System.out.println(c1.getName());
}
}
5、取得Person类的属性