配置文件
classname=itheima001.Student mathodname = study
自定义注解
package itheima001; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface myAnnotation2 { String classname(); String mathodname(); }
类
package itheima001; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; @myAnnotation2(classname = "itheima001.Student",mathodname = "study") public class myAnnotationtest2 { public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { // //通过配置文件class.txt调用Student中的study方法 // Properties p=new Properties(); // FileReader fr=new FileReader("myannotation\\class.txt"); // p.load(fr); // fr.close(); // // // String classname = p.getProperty("classname"); // String mathodname = p.getProperty("mathodname"); 通过注解调用Student中的study方法 Class<myAnnotationtest2> cc = myAnnotationtest2.class; myAnnotation2 annotation = cc.getAnnotation(myAnnotation2.class); String classname = annotation.classname(); String mathodname = annotation.mathodname(); Class<?> c = Class.forName(classname); Constructor<?> con = c.getConstructor(); Object o = con.newInstance(); Method method = c.getMethod(mathodname); method.invoke(o); } }