There are three ways to get a class
entity classes and Interfaces
Public interface Person {
public void Sayhi ();
}
public class Student implements person{
Private String ID;
private String name;
private int age;
public int sex=1;
/*get and Set methods omitted */
Public Student () {super ();}
Public Student (string ID, string name, Int. age) {
Super ();
This.id = ID;
THIS.name = name;
This.age = age;
}
}
Class C1 = Student.class;
Class c2=class.forname ("com.study.reflect.Student"); You must bring the package name here.
Class c3=new Student (). GetClass ();
System.out.println (C1==C2);
System.out.println (C1==C3);
System.out.println ("Class name" +c1.getname ()); Get class Name
Package Package1=c1.getpackage (); Get Package Name
SYSTEM.OUT.PRINTLN ("Package name" +package1.getname ());
SYSTEM.OUT.PRINTLN ("Interface Name" +c1.getinterfaces () [0].getname ()]; Interface Name Com.study.reflect.Person
System.out.println ("Parent class" +c1.getsuperclass ()); Parent class Java.lang.Object
Output: True True
Why are all true:
First you have to understand that in Java any class to be loaded on the virtual machine to run, the above three ways is the JVM to find and load the specified class, since all are the same class, then the results must be the same!
2. Use Newinstance () to go back to the instance object of the class
Class C1 = Student.class;
Student o = (Student) c1.newinstance ();
O.setname ("Chenjun");
System.out.println (O.getname ());
3. Get all the properties of a class, including common and private properties (GetField can only get common attributes, Getdeclaredfield may get common and private properties)
Field Field=c1.getfield ("sex"); To get a specific property
field[] fields = C1.getfields (); Get all the public properties
Field Field3=c1.getdeclaredfield ("name"); Get private Property
field[] Fields4 = C1.getdeclaredfields (); Get all properties (public and private)
4. Get the method
/Get non-parametric construction method
Constructor com1 = C1.getconstructor (null);
System.out.println (Com1.getparametertypes (). length); Output 0
Constructor Com=c1.getconstructor (String.class,string.class,int.class); constructor method for invoking a specific parameter type
Output java.lang.String java.lang.String int output is the parameter type
For (Class a:com.getparametertypes ()) {
System.out.println (A.getname ());
}
Output is java.lang.class input raw data type
For (Type a:com.getgenericparametertypes ()) {
System.out.println (A.getclass (). GetName ());
}
5. Get Other methods
method = C1.getmethod ("Setage", Int.class); Gets the specified method
Method[] Methods=c1.getmethods (); Get all the methods
This article is from the "Programmer rookie" blog, be sure to keep this source http://5345468.blog.51cto.com/5335468/1689091
Reflection acquisition class, property, method, interface, parent class, etc.