现在的位置: 首页 > 综合 > 正文

Java使用反射、自定义注解注入对象

2018年02月06日 ⁄ 综合 ⁄ 共 2408字 ⁄ 字号 评论关闭

自己写的一个小例子,记录一下。

package com.lxq.annotationAndreflection;

public class Person
{
	String name="default";
	Integer age=0;
	
	public Person()
	{
		super();
	}
	public Person(String name, Integer age)
	{
		super();
		this.name = name;
		this.age = age;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public Integer getAge()
	{
		return age;
	}
	public void setAge(Integer age)
	{
		this.age = age;
	}
	
}

package com.lxq.annotationAndreflection;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface SelfAnnotation
{
	String name();
}

package com.lxq.annotationAndreflection;

public class Injection
{
	@SelfAnnotation(name = "Person")
	static Person person;
	public void show()
	{
		System.out.println(person.getName()+","+person.getAge());
	}

}

package com.lxq.annotationAndreflection;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test
{
	public static void main(String[] args) throws Exception
	{
		//取得Injection的类描述类
		Class<Injection> clazz=Injection.class;
		//取得所有的字段描述对象
		Field[] fields=clazz.getDeclaredFields();
		System.out.println(fields.length);
		for(Field field:fields){
			//取得每个字段上面的注解对象
			Annotation[] annotations=field.getDeclaredAnnotations();
			System.out.println(annotations.length);
			for(Annotation annotation:annotations){
				//判断注解对象是不是SelfAnnotation类型的
				if(annotation.annotationType()==SelfAnnotation.class){
					System.out.println("yes");
					//通过SelfAnnotation的name获取要使用的beanName
					String beanName=((SelfAnnotation) annotation).name();
					//生成一个Peron的类描述类
					Class<?> cc=Class.forName("com.lxq.annotation."+beanName);	
					//生成一个Person对象
					Object ob=cc.newInstance();
					System.out.println(field.getName());
					//通过此方法将新建的实例对象赋值给 static Peron person
					//如果是非static,那么set的第一个参数必须指定实例对象,也就是哪个Injection对象
					field.set(null, ob);
					//获取名字为show的方法
					Method method=clazz.getDeclaredMethod("show");
					//调用该方法
					method.invoke(clazz.newInstance());
					
					//基本和上面的一样,只是生成Person对象时,反射调用了带参数的构造
					Class<?> c2=Class.forName("com.lxq.annotation."+beanName);	
					Class<?>[] ptype=new Class[]{String.class,Integer.class};
					Constructor<?> ctor=c2.getConstructor(ptype);
					Object[] obj=new Object[]{new String("lxq"),new Integer(25)};
					Object object=ctor.newInstance(obj);
					field.set(null, object);
					Method method2=clazz.getDeclaredMethod("show");
					method2.invoke(clazz.newInstance());
				
				}
			}
		}
		//因为 static Peron person,所以新建的Injectin对象的Peron对象都是通过反射最后赋值过得
		Injection injection=new Injection();
		System.out.println(injection.person.getName()+","+injection.person.getAge());
		
	}
}

抱歉!评论已关闭.