反射获取对象示例

Student实体类

package com.bean;

//定义实体类
@CustomAnnotation("jock")
public class Student extends Creature<String> implements Comparable<String>, CustomInterface {
	private static final long serialVersionUID = 243884481534779994L;
	int id;
	public String name;
	private int age;

	public Student() {
	}

	public Student(String name) {
		this.name = name;
	}

	@CustomAnnotation
	private Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	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;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public int compareTo(String o) {
		return 0;
	}

	@CustomAnnotation(value = "hpeu")
	@Override
	public void show() {
		System.out.println("我是一个学生!");
	}

	private Integer spreak(String language, Integer year) throws Exception {
		System.out.println("我的喜欢:" + language);
		return year;
	}

	public static void info() {
		System.out.println("开发工程师!");
	}

	class Bird {
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

反射获取Student对象

package com.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

// 反射获取Student对象
public class StudentReflection {
	public static void main(String[] args) throws Exception {
		Class clazz = Class.forName("com.bean.Student");//包名的完整路径
		// 获取包名
		Package package1 = clazz.getPackage();
		System.out.println(package1);
		System.out.println();
		
		// 获取注解
		Annotation[] annotations = clazz.getAnnotations();
		for(Annotation annotation : annotations) {
			System.out.println(annotation);
		}
		
		// 获取类的访问修饰符
		System.out.print(Modifier.toString(clazz.getModifiers()) + " class ");
		System.out.print(clazz.getSimpleName() + " ");
		// 获取泛型父类
		Type superclass = clazz.getGenericSuperclass();
		if (superclass != null) {
			System.out.print("extends ");
		}
		// 获取泛型类型
		//ParameterizedType ptype = (ParameterizedType)superclass;
		//Type[] actualType = ptype.getActualTypeArguments();
		//String xx = actualType[0].getTypeName();
		//System.out.println(" ====" + xx + " =====" );
		System.out.println(superclass);
		
		// 获取接口
		Class[] interfaces = clazz.getInterfaces();
		if (interfaces != null && interfaces.length > 0) {
			System.out.print(" implements ");
		}
		for(int i = 0; i<interfaces.length; i++) {
			System.out.print(interfaces[i].getSimpleName());
			if (i < interfaces.length - 1) {
				System.out.print(",");
			}
		}
		
		System.out.print("{");
		System.out.println();
		
		// 获取所有属性
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields) {
			// 获取属性的修改符 public String name;
			System.out.print("    ");
			System.out.print(Modifier.toString(field.getModifiers()) + " ");
			System.out.print(field.getType().getName() + " ");
			System.out.print(field.getName() + ";");
			System.out.println();
		}
		
		System.out.println();
		
		// 获取构造器 public Student(String name)
		Constructor[] cons = clazz.getDeclaredConstructors();
		for(Constructor con : cons) {
			// 获取构造方法上的注解
			Annotation[] ans = con.getAnnotations();
			for(Annotation an : ans) {
				System.out.println("    " + an);
			}
			System.out.print("    ");
			// 获取构造器的访问修饰符
			System.out.print(Modifier.toString(con.getModifiers()) + " ");
			// 获取构造器的名称
			System.out.print(con.getName() + "(");
			// 获取构造器参数
			Class[] pts = con.getParameterTypes();
			for(int i=0; i<pts.length; i++) {
				System.out.print(pts[i].getSimpleName() + " arg" + i);
				if (i < pts.length - 1) {
					System.out.print(",");
				}
			}
			System.out.println(") {");
			System.out.println("    }");
		}
		
		System.out.println();
		
		// 获取方法
		// private Integer spreak(String language, Integer year) throws Exception {
		Method[] methods = clazz.getDeclaredMethods();
		for(Method method : methods) {
			// 获取方法上的注解
			Annotation[] ans = method.getAnnotations();
			for(Annotation an : ans) {
				System.out.println("    " + an);
			}
			System.out.print("    ");
			// 获取方法的访问修饰符
			System.out.print(Modifier.toString(method.getModifiers()) + " ");
			// 获取方法返回值类型
			Class<?> type = method.getReturnType();
			System.out.print(type.getSimpleName() + " ");
			
			// 获取方法名称
			System.out.print(method.getName() + "(");
			// 获取方法参数列表
			Class<?>[] pts = method.getParameterTypes();
			for(int i=0; i<pts.length; i++) {
				System.out.print(pts[i].getSimpleName() + " arg" + i);
				if (i < pts.length - 1) {
					System.out.print(",");
				}
			}
			System.out.print(")");
			// 获取方法的异常
//			Class<?>[] exes = method.getExceptionTypes();
//			System.out.println("----" + exes.getClass().getName());
//			if (exes != null || exes.length > 0) {
//				System.out.print(" throws ");
//			}
			System.out.println("{");
			System.out.println("    }");
			
			System.out.println();
		}		
		System.out.print("}");
	}
}

反射的使用演示

package com.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import org.junit.Test;

/**
 * 反射的使用演示
 * Class类:
 * Class类是反射的根源,运行时对象中所有的信息都存储在此对象中。
 * 对象是什么时候加载到内存中的?
 * 1. 编写Java代码;
 * 2. 运行javac.exe命令来编译Java文件,生成Java的字节码文件(.class);
 * 3. 通过执行java.exe命令来加载.class到内存,并解释执行此文件;
 * 此时,被加载到内存中的对象就是一个Class的运行时对象。运行时对象会在内存中
 * 暂缓一定时间,便于使用。并且此运行时对象在内存中只有一份。
 */
public class ReflectionTest01 {
	// 使用反射
	@Test
	public void test2() throws Exception {
		// 1. 获取了内存中的运行时对象
		Class<Person> clazz = Person.class;//Person是自定义的类
		
		// 2. 获取运行时对象的构造器
		Constructor<Person> constructor = clazz.getDeclaredConstructor(String.class, int.class);
		
		// 3. 通过获取到的构造器来实例化运行时的类对象
		Person person = constructor.newInstance("李四", 28);
		System.out.println(person);
		
		// 4. 通过反射的方式调用方法
		//person.say();
		Method say = clazz.getDeclaredMethod("say");
		// 调用方法
		say.invoke(person);
		
		Method fun = clazz.getDeclaredMethod("fun", String.class);
		fun.setAccessible(true);
		String str = (String) fun.invoke(person, "重庆");
		System.out.println(str);
	}
	
	
	// 不使用反射
	@Test
	public void test1() {
		Person person = new Person("张三", 20);
		System.out.println(person);
		
		person.setAge(25);
		System.out.println(person);
		
		person.say();
		
		// person.fun();
	}	
}

Person实体类

package com.reflect;

@SuppressWarnings("unused")
public class Person {
	private String name;
	int age;
	public String gender;

	private Person(String name) {
		this.name = name;
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Person() {
		System.out.println("------调用了无参构造--------");
	}

	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 fun(String name) {
		return name + "天太热了。";
	}
	
	public void say() {
		System.out.println("大家好!");
	}
	
	public static int print(String name, int age) {
		return name.hashCode() + age;
	}
	
	public static void speak() {
		System.out.println("speak()------");
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值