Introduction to Simple Principles Java Reflection (2)

Source: Internet
Author: User

public class Person {private string name;private int age;public person (String Name,int age) {super (); this.name = Name;this . Age = Age;} Public Person   () {}public String getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "person [name=" + name + ", age=" + Age + "]";} public void Show () {System.out.println ("show");} public void Fun (String str) {System.out.println (str);} public static void function () {System.out.println ("static");}}
public class Demo1 {/** * Reflection: Dynamically acquires a bytecode file object (Person.class) and runs on its members * * Dynamic acquisition of bytecode file objects: * 1: Any object is created by a bytecode file object, so any object can Get your own bytecode file object * Then this function should be defined in object, so using GetClass () * Requires a new object * * 2: Each data type has a static class attribute, which can be used to get the bytecode file object * Do not need n EW object, but requires the person class to exist * * The 3:class class provides a static forname (String str) method * Only needs to provide the package name in string form + class name * @throws classnotfoundexception */          public static void Main (string[] args) throws ClassNotFoundException {Getclaz ();          GETCLAZ2 (); GetClaz3 ();} The class class provides a static, fornamepublic static void GetClaz3 () throws classnotfoundexception{class<?> Claz1 = Class.forName ("Com.qianfeng.reflect.Person"); class<?> claz2 = Class.forName ("Com.qianfeng.reflect.Person"); System.out.println (CLAZ1==CLAZ2);} Get the bytecode file object by static property Class public static void GetClaz2 () {class<person> claz1 = Person.class; class<person> claz2 = Person.class; System.out.println (CLAZ1==CLAZ2);} 1: Use GetClass () in object to get the bytecode file object public static void Getclaz () {//person Person1 = New person ();//Load Person.class to method area//class&lt first; Extends person> claz1 = Person1.getclass ();//Got Person.class////person Person2 = new Person ();//class<? Extends person> claz2 = Person2.getclass ();//Got Person.class////system.out.println (CLAZ1==CLAZ2);//true}}

Import Java.lang.reflect.constructor;import Java.lang.reflect.invocationtargetexception;public class Demo2 {/** * Get the bytecode file object dynamically and create the object * @throws illegalaccessexception * @throws instantiationexception * @throws classnotfoundexception * @throws invocationtargetexception * @throws illegalargumentexception * @throws SecurityException * @throws Nosuchmethod Exception */public static void Main (string[] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, Nosuchmethodexception, SecurityException, IllegalArgumentException, invocationtargetexception {createObj1 (); CreateObj2 ();} Create objects using the constructed method with parameters public static void CreateObj2 () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{//person person = new Person ("Little Red", 20);//Get Bytecode File object---person.classclass<?> Claz = Class . forname ("Com.qianfeng.reflect.Person");//Gets the object of the constructor type to which the constructor method belongs ConstruCtor<?> constructor = Claz.getconstructor (String.class,int.class);// Creating objects using construction methods--using constructor to provide the ability to create objects person person = (person) constructor.newinstance ("Little Red", 20); SYSTEM.OUT.PRINTLN (person);} instantiationexception//occurs when the constructor method of the null parameter does not exist, illegalaccessexceptionpublic static void CreateObj1 () occurs when the permission of the constructor method is too low. Throws ClassNotFoundException, instantiationexception, illegalaccessexception{//person person = new person ();// Gets the bytecode file object---person.classclass<?> Claz = class.forname ("Com.qianfeng.reflect.Person");// Use the Newinstance () method provided by class to create objects of type Person Object obj = claz.newinstance ();//create object with NULL parameter construction method Person person = (person) obj; SYSTEM.OUT.PRINTLN (person);}}

Import Java.lang.reflect.field;public class Demo3 {/** * Dynamically create objects and assign values to properties * @throws ClassNotFoundException * @throws Security Exception * @throws nosuchfieldexception * @throws illegalaccessexception * @throws instantiationexception */public St atic void Main (string[] args) throws ClassNotFoundException, Nosuchfieldexception, SecurityException, Instantiationexception, illegalaccessexception {//person person = new Person ();//person.setname ("Little Red");//          Gets the bytecode file object---person.class class<?> claz = Class.forName ("Com.qianfeng.reflect.Person"); Gets the property name that belongs to the field type of the object//field field = Claz.getfield ("name");//Only the permission is public property//system.out.println (Field);//n          osuchfieldexception Field field = Claz.getdeclaredfield ("name");          Because name is a non-static property, it must be accessed through an object, so object obj = Claz.newinstance () is created first;          Set the Name property to accessible field.setaccessible (TRUE);//The method is inherited from the parent class//Use the assignment function provided by the field class to assign a value to the attribute Field.set (obj, "Little Red");      System.out.println (obj);    }} 

Import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;public class Demo4 {/** * Dynamically create objects,  and call method * @throws invocationtargetexception * @throws illegalargumentexception * @throws illegalaccessexception * @throws Instantiationexception * @throws SecurityException * @throws nosuchmethodexception * @throws classnotfoundexception * /public static void Main (string[] args) throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {method1 (); Method2 (); Method3 ();} Call static method public static void Method3 () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{//gets the bytecode file object---person.class Class<?          > Claz = Class.forName ("Com.qianfeng.reflect.Person");          Gets the object of the method type to which the invoked methods belong: Method = Claz.getmethod ("function", null);     Execution methodMethod.invoke (null, NULL); }//calls the constructed method with parameters public static void Method2 () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{//        Gets the bytecode file object---person.class class<?> claz = Class.forName ("Com.qianfeng.reflect.Person");          Gets the object of the method type to which the called Methods Belong: Method method = Claz.getmethod ("Fun", string.class);          Fun () is a non-static method that requires an object to be invoked to invoke object obj = Claz.newinstance (); Execution method Method.invoke (obj, "Hello");} Calling an parameterless construction method public static void Method1 () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, illegalargumentexception, invocationtargetexception{//person person = new Person ();p erson.show ();//Get Bytecode File object---person.class class<?> claz = Class.forName ("Com.qianfeng.refl Ect.          Person ");      Gets the object of the method type to which the called methods belong, method = Claz.getmethod ("show", null);         Show () is non-static and requires that the object be invoked to invoke object obj = Claz.newinstance ();          Execution method Method.invoke (obj, null); }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to Simple Principles Java Reflection (2)

Related Article

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.