package Reflects;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
注解练习1
*/
@LoadClassTest(ClassName="Reflects.Student",ClassMethod = "study")
public class ReflectDemo{
public static void main(String[] args) throws Exception{
Class<ReflectDemo> rdc = ReflectDemo.class;
LoadClassTest a = rdc.getAnnotation(LoadClassTest.class);
String classMethod = a.ClassMethod();
String className = a.ClassName();
Class<?> aClass = Class.forName(className);
Constructor<?> constructor = aClass.getConstructor();
Object o = constructor.newInstance();
//获取对应的方法
Method method = aClass.getMethod(classMethod);
method.invoke(o);
}
}
package Reflects;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE) //作用在类上
@Retention(RetentionPolicy.RUNTIME)
public @interface LoadClassTest {
String ClassName();
String ClassMethod();
}