Java Learning Series (20) Java Object-oriented reflection

Source: Internet
Author: User


Reprint Please specify Source:http://blog.csdn.net/lhy_ycu/article/details/45289391


Objective

Today, talk about reflection in Java. Our common reflection is used for the load driver Class.forName ("Com.mysql.jdbc.Driver") in JDBC, the MVC of struts, the ORM in Hibernate, the IOC in spring and some other frameworks, and more. What good does it have? It has the advantage of being able to dynamically create objects and compile and have access to all (including private) attribute methods and objects in a class and to invoke the property methods and make them more flexible, which also helps to reduce the coupling between classes, but the reflection also has the disadvantage that it destroys the encapsulation of the class and the integrity of the object.



Example description
/** * Target class * * @author [* Reproduced yesterday *] [email protected] * @since version 1.0 * @datetime April 26, 2015 afternoon 4:50:28 */public clas s Student {private String name;private Integer age;/** * No parameter constructs and assigns default value */public Student () {this.name = "Zhang San"; this.age = 22;} Public Student (String name, Integer age) {this.name = Name;this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Integer Getage () {return age;} public void Setage (Integer age) {this.age = age;} public void info () {System.out.println ("Be a happy programmer ~" + this);} private void Joke () {System.out.println ("a joke ... ");} No public void Play () {System.out.println (THIS.name + "is playing ...");} Overloaded playpublic void Play (String name) {System.out.println (THIS.name + "is playing xx with" + name);} /** * GetClass (). GetName () + "@" + integer.tohexstring (Hashcode ()); * Recommended entity Classes overwrite ToString method for easy viewing of log information * * @return * @see java.lang.object#tostring () */@Overridepublic String toString () {return "Student [name=" + name +", age=" + Age + "]";}} 

Target Test class
/** * Use reflection to test the target class * * @author [* Reproduced yesterday *] [email protected] * @since version 1.0 * @datetime April 26, 2015 afternoon 5:14:52 */pu Blic class Studenttest {@BeforeClasspublic static void Beforeclass () {System.out.println ("========= Execute--beforeclass=====\n "before all test methods are executed);} /** * 1, Class.forName ("Package-name"), 2, Student.class;3, Obj.getclass () * * @throws Exception */@Testpublic void TestInfo () throws Exception {class<?> C1 = class.forname ("com.leo.reflection.Student");//Class<?> C1 = Student.class;//Gets the example, newinstance () calls the parameterless constructor by default, so the target class is required to keep the parameterless constructor Student S1 = (Student) c1.newinstance ();// System.out.println ("S1 =" + S1.getclass (). Getcanonicalname ()); S1.info (); int age = S1.getage (); String name = S1.getname (); Assert.assertthat (age, matchers.is);//Normalassert.assertthat (name, matchers.is ("John Doe"));//failure}/** * Get a class by the loader of the class * * @throws Exception */@Testpublic void TestInfo2 () throws Exception {//Get a classloader classloader cl = Classloa Der.getsystemclassloader ();//load the specified class class<?> Clazz = Cl.loadclass ("com.leo.reflection.Student");//System.out.println (Clazz.getname ()); Student S1 = (Student) clazz.newinstance (); S1.info ();} /** * Access Builder * * @throws Exception */@Testpublic void Testconstruction () throws Exception {class<?> C1 = Class.forna Me ("com.leo.reflection.Student");//Gets the constructor object with the constructor method with the specified argument list constructor<?> cs = C1.getdeclaredconstructor (String.class,integer.class); Student S1 = (Student) cs.newinstance ("small Four"), S1.info ();//Gets all constructors for the specified class//constructor<?>[] Constructors = C1.getdeclaredconstructors ();//For (constructor<?> constructor:constructors) {//System.out.println (" constructor = "+ constructor);//}}/** * Access properties (including private properties) * * @throws Exception */@Testpublic void Testfield () throws Except Ion {class<?> C1 = Class.forName ("com.leo.reflection.Student"); Student S1 = (Student) c1.newinstance ();//Gets an attribute field field = C1.getdeclaredfield ("name");// This property is set to accessible field.setaccessible (true); System.out.println ("field =" + Field + "," + fieLd.get (S1));//Gets all properties of the specified class//field[] fields = C1.getdeclaredfields ();//For (Field f:fields) {//F.setaccessible (TRUE);// System.out.println (F.getname () + "=" + F.get (S1)),//}}/** * Access method (including Private method) * * @throws Exception */@Testpublic void tes TMethod () throws Exception {class<?> C1 = class.forname ("com.leo.reflection.Student"); Student S1 = (Student) c1.newinstance ();//Gets the specified non-parametric method of a class M1 = C1.getdeclaredmethod ("Play"); M1.invoke (S1);// Gets the specified method of a class with parameter methods m2 = C1.getdeclaredmethod ("Play", String.class); M2.invoke (S1, "money Seven"); System.out.println ("=======================");//Gets all methods of the specified class//method[] methods = C1.getdeclaredmethods ();//For ( Method method:methods) {//Method.setaccessible (TRUE);//System.out.println (Method.getname ());//}// System.out.println ("=======================\n");} @AfterClasspublic static void Afterclass () {System.out.println ("========== executes--afterclass=====\n after all test methods are executed");}}



Summary 1, all classes of objects are actually instances of class.   2. When class instantiates objects of other classes, be sure to keep the default parameterless constructor. 3.3 Common ways to load a class: a) Class.forName ("Full Path to Class"), B) class name. class, C) Obj.getclass () 4, common two-step:class<?> of Reflection C1 = Class.forName ( "The full path of the class"); T1 t = (T1) c1.newinstance ();



Java Learning Series (20) Java Object-oriented reflection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.