Java Learning Note (61)-Reflection reflection

Source: Internet
Author: User

Reflective Reflection
Import Java. Lang. Reflect. Modifier;/ * * Reflection Reflection * Java.lang.Class Class * *public class Test01 {public static void main (string[] args) {String name ="Tom";Way one: Through the object GetClass () method//object of any class, there is a getclass () method//Can get the class object of the type of the current object.CLS= Name. GetClass();Showinfo (CLS);Mode two: Through the class forname () static method try {class Cls2=class. forname("com.itany.basejava.day37.Test01");Showinfo (CLS2);} catch (ClassNotFoundException e) {E. Printstacktrace();}//Way Three: Class Cls3=student by specifying classes. Class;Showinfo (CLS3);}//Gets information about the class object public static void Showinfo (classCLS) {System. out. println("The full name of the class:"+CLS. GetName());System. out. println("class name:"+CLS. Getsimplename());System. out. println("Owning package:"+CLS. Getpackage());System. out. println("is a local class:"+CLS. Islocalclass());System. out. println("Whether it is an interface:"+CLS. Isinterface());System. out. println("is an array:"+CLS. IsArray());System. out. println("is the base data type:"+CLS. Isprimitive());Gets the class object of its parent class, class Supercls =CLS. Getsuperclass();System. out. println("Parent class's full name:"+ SUPERCLS. GetName());Gets the modifier of the class int m =CLS. GetModifiers();System. out. println("modifier is:");if (Modifier. IsPublic(m)) {System. out. Print("Public");} if (Modifier. IsStatic(m)) {System. out. Print("Static");} if (Modifier. IsAbstract(m)) {System. out. Print("Abstract");} if (Modifier. IsFinal(m)) {System. out. Print("Final");} System. out. println("**************************************\n");}}
To instantiate an object by using reflection to access the construction method
Import Java.lang.reflect.constructor;import Java.lang.reflect.Method;/* * The object is instantiated through the reflection access construction method * Constructor class * / Public classTest03 { Public Static void Main(string[] args) throws Exception {//Create an object of the dog class        //Dog Dog1=new dog ("Rhubarb", 3, "male");        //Create a Class object of the dog classclass<dog> cls = Dog.class;/ * * Instantiate an object without a parameter constructor, both ways */        //1. Create an instance from the Newinstance () method of the Class object, only for creating objects by using the parameterless construction methodDog dog = (dog) cls.newinstance ();//Dog.show ();method = Cls.getdeclaredmethod ("Show");        Method.invoke (dog); System. out. println ("*************************\n");//2. Get the constructor method with null parameterConstructor C = Cls.getdeclaredconstructor ();        Dog dog2 = (dog) c.newinstance ();        Dog2.show (); System. out. println ("*************************\n");/ * Instantiate the object with the parameter construction method */Constructor C2 = Cls.getdeclaredconstructor (NewClass[] {string.class,int. class, String.class}); Dog Dog3 = (dog) c2.newinstance ("Little Yellow",2,"female"); Dog3.show ();/ * * Instantiate an object through a private-modified construction method */constructor<dog> C3 = Cls.getdeclaredconstructor (NewClass[] {string.class, string.class}); C3.setaccessible (true); Dog Dog4=c3.newinstance ("Big Yellow","Medium");    Dog4.show (); }}/ * * Animal Parent class * /Class Animal { PublicString name;intAge Public Animal() {System. out. println ("How to construct a parent class without a parameter"); } Public Animal(String name,intAge) { This. name = name; This. Age = Age; System. out. println ("constructor method with parameters in parent class"); } Public void Show() {System. out. println ("Show method in parent class"); }}/ * * Dog class, inherited from Animal */Class Dog extends Animal {String sex; Public Dog() {System. out. println ("constructor method for no arguments in subclasses"); } Public Dog(String name,intAge, String Sex) {System. out. println ("constructor method with parameters in subclasses"); }Private Dog(string name, string sex) {System. out. println ("Construction method with two parameters in subclasses"); }//Override the Show method in the parent class     Public void Show() {System. out. println ("Show methods in subclasses"); }}
Field class
Import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.Method ;/ * * Field class */ Public classTest02 { Public Static void Main(string[] args) throws SecurityException, Nosuchfieldexception, IllegalArgumentException, ILLEGALACC Essexception, Nosuchmethodexception, invocationtargetexception {//Create an object of the student class, that is, the student objectStudent STU1 =NewStudent (); Student STU2 =NewStudent ();//Create a Student class object, which is the class object of the student classesClass cls = Student.class;/ * * Field property operation; */        //1. Gets all the attributes in the student class, including all the public adornments in this class and the parent class        //field[] fields = Cls.getfields ();        //2. Gets all the attributes in the student class, including any properties decorated by any modifier in this classfield[] fields = Cls.getdeclaredfields (); for(Field f:fields) {System. out. println (F.getname ());//System.out.println (f.tostring ());} System. out. println ("**********************\n");//3. Get the properties specified in the Student classField name = Cls.getfield ("Name"); Field grade = Cls.getdeclaredfield ("Grade"); Field sex = Cls.getsuperclass (). Getdeclaredfield ("Sex");//Assign a value to a property        //Stu1.name= "Tom";//directly through the object name. Property name AssignmentName.Set(STU1,"Alice");//Assign a value to the property of the specified objectSystem. out. println ("STU1 's name:"+ Name.Get(STU1));//Set property to accessible, that is, set access modifierGrade.setaccessible (true); Grade.Set(STU1,2);//Assignment for STU1 's private property gradeSystem. out. println ("STU1 's Grade:"+ grade.Get(STU1)); System. out. println ("*****************************************\n");/ * Method Operation */        //1. Get all the methods in the Student class        //method[] methods = Cls.getmethods ();Method[] Methods=cls.getdeclaredmethods (); for(Method m:methods) {System. out. println (M.getname ()); }//2. Get the method specified in the Student class        //stu1.calc (ten);Class[] args1={int. class,Double. class}; Method Calc=cls.getmethod ("Calc", ARGS1); Object[] args2={Ten,25.4};DoubleSum= (Double) Calc.invoke (STU1, ARGS2); System. out. println ("The sum of two counts is:"+sum);//Get the private adornment methodMethod Show=cls.getdeclaredmethod ("Show"); Show.setaccessible (true);//Do not detect access modifiersShow.invoke (STU2);//Call method}}/ * * Person class */Class Person { PublicString name;intAgePrivateString sex;protected DoubleHeight;}/ * * Student class, inherited from person */Class Student extends Person { Public intId//Study No.    Private intGrade//Grade numberString ClassName;//class name     Public Student(){    } Public int Getgrade() {returnGrade } Public void Setgrade(intGrade) { This. grade = grade; } Public int Calc(intNUM1,intNUM2) {returnNUM1 + num2; } Public Double Calc(intNUM1,DoubleNUM2) {returnNUM1 + num2; }Private void Show() {System. out. println ("Sixth row right number two people a bit 22222"); }}

Java Learning Note (61)-Reflection reflection

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.