1:SUN提供的反射机制的类:java.lang.Class java.lang.reflect.Constructor JAVA反射机制是在运⾏状态中,对于任意⼀个类。都能都知道这个类的所有属性和⽅法,对于任意⼀个对象,都能够调⽤它的任意⼀个⽅法和属性;这种动态获取的信息以及动态调⽤对象的⽅法的功能称之为java语⾔的反射机制;3:反射的作⽤反编译 .class --à .java 通过反射机制可以访问java对象中的属性,⽅法,构造⽅法4:创建Class对象的三种⽅式JavaBean: public class Person implements China{ private String name; private int age ; private char sex ; public Person() { super (); } public Person(String name, int age, char sex) { super (); this .name = name; this .age = age; this .sex = sex; } 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; } public char getSex() { return sex ; } public void setSex(char sex) { this .sex = sex; } public void eat() { System. out .println(\"吃了\" ); } @Override public String toString() { return \"Person [name=\" + name + \ } @Override public void sayChina() { // TODO Auto-generated method stub System. out .println(\"作者:\" + AUTHOR + \"国籍:\"+ NATIONAL ); } @Override public String sayHello(String name, int age, char sex) { // TODO Auto-generated method stub return \"姓名:\" + name + \"年龄:\"+ age + \"性别:\" + sex; }} 1 public class ClassDemo02 { 2 3 public static void main(String[] args) { 4 Person p1 = new Person(\"⼩明\" ,20,'男' ); 5 Person p2 = new Person(\"⼩红\" ,23,'⼥' ); 6 7 //创建Class对象的⽅式⼀:(对象.getClass()),获取person类中的字节码⽂件 8 Class class1 = p1.getClass(); 9 System. out.println(p1.getClass().getName());10 Class class2 = p2.getClass(); 11 System. out.println(class1 == class2 );12 13 System. out.println(\"==============================\" ); 14 //创建Class对象的⽅式⼆:(类.class:需要输⼊⼀个明确的类,任意⼀个类型都有⼀个静态的class属性)15 Class class3 = Person.class; 16 System. out.println(class1 == class2);17 18 System. out.println(\"==============================\" ); 19 //创建Class对象的⽅式三:(forName():传⼊时只需要以字符串的⽅式传⼊即可) 20 //通过Class类的⼀个forName(String className)静态⽅法返回⼀个Class对象,className必须是全路径名称;21 //Class.forName()有异常:ClassNotFoundException22 23 Class class4 = null;24 try { 25 class4 = Class.forName(\"cn.itcast.Person\");26 } catch (ClassNotFoundException e) {27 // TODO Auto-generated catch block28 e.printStackTrace();29 } 30 System. out.println(class4 == class3);31 }32 } 注意:在开发中⼀般使⽤第三种⽅法,因为第三种接收的是⼀个字符串路径,将来可以通过配置⽂件获取,通⽤性好;4:newInstance()⽅法 ---> 获取class类型之后,可以创建该类型的对象 public T newInstance()throws InstantiationException,IllegalAccessException 1 public class reflect03 { 2 3 public static void main(String[] args) throws Exception { 4 5 Class c1 = Class.forName(\"com.itheima04.Test_20171106.Test_20171207.Person\"); 6 7 //创建此Class对象所表⽰类的⼀个新实例, 8 //newInstance⽅法调⽤的是Person的空参数构造⽅法 9 Object o = c1.newInstance();10 System.out.println(o.toString());11 } 因篇幅问题不能全部显示,请点此查看更多更全内容