package com.sxt;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 反射
* @author Administrator
*
*/
public class User {
public String name;
private int age;
public User(){
}
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
private void run() {
System.out.println("我会跑");
}
public void say() {
System.out.println("我会说话");
}
@SuppressWarnings("unused")
private void run(String name) {
System.out.println(name+"我会跑");
}
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//加载这个类class文件
Class c = Class.forName("com.sxt.User");
//创建一个实例化的路径
User u =(User) c.newInstance();
//1.类的全路径
System.out.println("1.类的全路径:"+c.getName());
//2.类的名称
System.out.println("2.类的名称:"+c.getSimpleName());
//3.类的权限
System.out.println("3.类的权限:"+Modifier.toString(c.getModifiers()));
//4.是否是接口
System.out.println("4.是否是接口:"+c.isInstance(c));
//5.父类的全称
System.out.println("5.父类的全称:"+c.getSuperclass().getName());
//6.父类的名字
System.out.println("6.父类的名字:"+c.getSuperclass().getSimpleName());
System.out.println("---------------------------------");
//1.获取public属性
Field f = c.getField("name");
System.out.println("1.获取public属性"+f.getName());
//2.获取所有public属性
Field[] fs = c.getFields();
System.out.println("2.获取所有public属性"+fs.length);
//3.获取所有类型的属性
Field[] dfs = c.getDeclaredFields();
System.out.println("3.获取所有类型的属性"+dfs.length);
//4.获取所有权限类的属性
Field gdf = c.getDeclaredField("age");
System.out.println("4.获取所有权限类的属性"+gdf.getName());
System.out.println("-----------------------------------");
//5.获取所有公共的方法包含父类接口
Method[] ms = c.getMethods();
for (Method m : ms) {
System.out.println(m.getName());
}
//6.通过方法名获取公共方法
Method m = c.getMethod("say");
System.out.println(m.getName());
//7.获取所有本类的方法
Method[] b = c.getDeclaredMethods();
for (Method bms : b) {
System.out.println(bms.getName());
}
//8.通过名字获取方法
Method bm = c.getDeclaredMethod("run");
System.out.println("8.通过名字获取方法"+bm.getName());
// 9.调用本类的带参数的方法
Method cm = c.getDeclaredMethod("run", String.class);
System.out.println("9.调用本类的带参数的方法");
cm.invoke(u, "张三");
}
}