狂神声明 : 文章均为本身的学习笔记 , 转载必定注明出处 ; 编辑不易 , 防君子不防小人~共勉 ! java
package com.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value={ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Annotation01 { String studentName() default ""; int age() default 0; int id() default -1; //String indexOf("abc") -1 String[] schools() default {"清华大学","北京大学"}; }
package com.test.annotation; /** * 测试自定义注解的使用 */ public class Demo02 { @Annotation01(age=22,studentName="狂神",id=10001,schools={"北京大学","清华大学"}) public void test(){} }
@AnnoTable("tb_student") public class Student { @AnnoField(columnName = "id",type="int",length = 10) private int id; @AnnoField(columnName = "studentName",type="varchar",length = 10) private String studentName; @AnnoField(columnName = "age",type="int",length = 3) private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
import java.lang.annotation.Annotation; import java.lang.reflect.Field; //使用反射读取注解的信息,模拟处理注解信息的流程 public class ReadAnno { public static void main(String[] args) { try { Class c = Class.forName("Student"); //得到类的全部有效注解 Annotation[] annotations = c.getAnnotations(); for (Annotation a:annotations){ System.out.println(a); } //得到类的指定注解 AnnoTable at = (AnnoTable)c.getAnnotation(AnnoTable.class); System.out.println(at.value()); //得到类的属性的注解 Field f = c.getDeclaredField("studentName"); AnnoField af = f.getAnnotation(AnnoField.class); System.out.println(af); System.out.println( af.columnName()+"--"+ af.length()+"--"+ af.type() ); //根据得到的表名,字段的信息,拼出DDL语句,而后 //使用JDBC执行这个SQL,在数据库中生成相关的表 } catch (Exception e) { e.printStackTrace(); } } }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = {ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface AnnoField { String columnName(); String type(); int length(); }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = {ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface AnnoTable { String value(); }
java的动态性程序员
动态语言数据库
Class c = Class.forName("com.kuangstudy.User")
加载完类以后 , 在堆内存中 , 就产生了一个Class类型的对象(一个类只有一个Class对象) , 这个对象就包含了完整的类的结构信息 . 咱们能够经过这个对象看到类的结构 , 这个对象就像一面镜子 , 透过这个镜子看到类的结构 , 因此咱们形象的称之为 : 反射 .编程
Class类介绍数组
Class类的对象如何获取 ?浏览器
//测试各类类型(class,interface,enum,annotation,primitive type,void)对应的java.lang.Class对象的获取方式 @SuppressWarnings("all") public class Demo01 { public static void main(String[] args) { String path = "com.test.bean.User"; try { Class clazz = Class.forName(path); //对象是表示或封装一些数据。 一个类被加载后,JVM会建立一个对应该类的Class对象,类的整个结构信息会放到对应的Class对象中。 //这个Class对象就像一面镜子同样,经过这面镜子我能够看到对应类的所有信息。 System.out.println(clazz.hashCode()); Class clazz2 = Class.forName(path); //一个类只对应一个Class对象 System.out.println(clazz2.hashCode()); Class strClazz = String.class; Class strClazz2 = path.getClass(); System.out.println(strClazz==strClazz2); Class intClazz =int.class; int[] arr01 = new int[10]; int[][] arr02 = new int[30][3]; int[] arr03 = new int[30]; double[] arr04 = new double[10]; System.out.println(arr01.getClass().hashCode()); System.out.println(arr02.getClass().hashCode()); System.out.println(arr03.getClass().hashCode()); System.out.println(arr04.getClass().hashCode()); } catch (Exception e) { e.printStackTrace(); } } }
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 应用反射的API,获取类的信息(类的名字、属性、方法、构造器等) */ public class Demo01 { public static void main(String[] args) { String path = "com.test.bean.User"; try { Class clazz = Class.forName(path); //获取类的名字 System.out.println(clazz.getName());//得到包名+类名:com.bjsxt.test.bean.User System.out.println(clazz.getSimpleName()); //获的类名:User //获取属性信息 // Field[] fields = clazz.getFields(); //只能得到public的field Field[] fields = clazz.getDeclaredFields();//得到全部的field Field f = clazz.getDeclaredField("uname"); System.out.println(fields.length); for(Field temp:fields){ System.out.println("属性:"+temp); } //获取方法信息 Method[] methods = clazz.getDeclaredMethods(); Method m01 = clazz.getDeclaredMethod("getUname", null); //若是方法有参,则必须传递参数类型对应的class对象 Method m02 = clazz.getDeclaredMethod("setUname", String.class); for(Method m:methods){ System.out.println("方法:"+m); } //得到构造器信息 Constructor[] constructors = clazz.getDeclaredConstructors(); Constructor c = clazz.getDeclaredConstructor(int.class,int.class,String.class); System.out.println("得到构造器:"+c); for(Constructor temp:constructors){ System.out.println("构造器:"+temp); } } catch (Exception e) { e.printStackTrace(); } } }
import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 经过反射API动态的操做:构造器、方法、属性 */ public class Demo01 { public static void main(String[] args) { String path = "com.test.bean.User"; try { Class<User> clazz = (Class<User>) Class.forName(path); //经过反射API调用构造方法,构造对象 User u = clazz.newInstance(); //实际上是调用了User的无参构造方法 System.out.println(u); Constructor<User> c = clazz.getDeclaredConstructor(int.class,int.class,String.class); User u2 = c.newInstance(1001,18,"测试一"); System.out.println(u2.getUname()); //经过反射API调用普通方法 User u3 = clazz.newInstance(); Method method = clazz.getDeclaredMethod("setUname", String.class); method.invoke(u3, "测试三"); //u3.setUname("测试三"); System.out.println(u3.getUname()); //经过反射API操做属性 User u4 = clazz.newInstance(); Field f = clazz.getDeclaredField("uname"); f.setAccessible(true); //这个属性不须要作安全检查了,能够直接访问 f.set(u4, "测试四"); //经过反射直接写属性 System.out.println(u4.getUname()); //经过反射直接读属性的值 System.out.println(f.get(u4)); } catch (Exception e) { e.printStackTrace(); } } }
反射机制性能问题安全
import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; /** * 经过反射获取泛型信息 */ public class Demo01 { public void test01(Map<String,User> map,List<User> list){ System.out.println("Demo01.test01()"); } public Map<Integer,User> test02(){ System.out.println("Demo01.test02()"); return null; } public static void main(String[] args) { try { //得到指定方法参数泛型信息 Method m = Demo01.class.getMethod("test01", Map.class,List.class); Type[] t = m.getGenericParameterTypes(); for (Type paramType : t) { System.out.println("#"+paramType); if(paramType instanceof ParameterizedType){ Type[] genericTypes = ((ParameterizedType) paramType).getActualTypeArguments(); for (Type genericType : genericTypes) { System.out.println("泛型类型:"+genericType); } } } //得到指定方法返回值泛型信息 Method m2 = Demo01.class.getMethod("test02", null); Type returnType = m2.getGenericReturnType(); if(returnType instanceof ParameterizedType){ Type[] genericTypes = ((ParameterizedType) returnType).getActualTypeArguments(); for (Type genericType : genericTypes) { System.out.println("返回值,泛型类型:"+genericType); } } } catch (Exception e) { e.printStackTrace(); } } }
反射操做注解(annotation)服务器
import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * 经过反射获取注解信息 */ public class Demo01 { public static void main(String[] args) { try { Class clazz = Class.forName("com.test.annotation.Student"); //得到类的全部有效注解 Annotation[] annotations=clazz.getAnnotations(); for (Annotation a : annotations) { System.out.println(a); } //得到类的指定的注解 tTable st = (tTable) clazz.getAnnotation(tTable.class); System.out.println(st.value()); //得到类的属性的注解 Field f = clazz.getDeclaredField("studentName"); tField tField = f.getAnnotation(tField.class); System.out.println(tField.columnName()+"--"+tField.type()+"--"+tField.length()); //根据得到的表名、字段的信息,拼出DDL语句,而后,使用JDBC执行这个SQL,在数据库中生成相关的表 } catch (Exception e) { e.printStackTrace(); } } }
Runtime run = Runtime.getRuntime();
Process process = run.exec("javac -cp d:/java/ Hello.java");
import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import java.lang.reflect.Method; import java.net.URLClassLoader; public class Demo01 { public static void main(String[] args) throws Exception { //经过IO流操做,将字符串存储成一个临时文件(Hi.java),而后调用动态编译方法! String str = "public class Hi {public static void main(String[] args){System.out.println(\"HaHa!\");}}"; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, "c:/myjava/HelloWorld.java"); System.out.println(result==0?"编译成功":"编译失败"); //经过Runtime调用执行类 // Runtime run = Runtime.getRuntime(); // Process process = run.exec("java -cp c:/myjava HelloWorld"); // // InputStream in = process.getInputStream(); // BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // String info = ""; // while((info=reader.readLine())!=null){ // System.out.println(info); // } try { URL[] urls = new URL[] {new URL("file:/"+"C:/myjava/")}; URLClassLoader loader = new URLClassLoader(urls); Class c = loader.loadClass("HelloWorld"); //调用加载类的main方法 Method m = c.getMethod("main",String[].class); m.invoke(null, (Object)new String[]{}); //因为可变参数是JDK5.0以后才有。 //m.invoke(null, (Object)new String[]{});会编译成:m.invoke(null,"aa","bb"),就发生了参数个数不匹配的问题。 //所以,必需要加上(Object)转型,避免这个问题。 //public static void main(String[] args) } catch (Exception e) { e.printStackTrace(); } } }