Java Reflection Technology (ii)

Source: Internet
Author: User
Tags array constructor integer reflection return tostring
Lesson:2 Processing Object


1.Creating Objects


in general, create an object by using the following methods


Rectangle r = new Rectangle ();


But if you are developing a development tools, you may not know the class to generate the object before you run it.


so you want to create objects like the following:


String ClassName;





//... load className from the user interface





Object o = new (ClassName); wrong!








But the above is wrong.


the correct way is to use the reflection property of a class:








1) Using no-argument Constructors


For example:


Class classdefinition = Class.forName (className);//Specify the Run-time instance of the class


object = Classdefinition.newinstance ();//The parameterless constructor is invoked to generate an instance of the specified class.





2) Using constructors that Have Arguments


This technique will use the following steps:


A, create a class object


B, create a constructor object, GetConstructor (class[] params) method, which is an array of classes appropriate to the construction method.


C, the Newinstance method is invoked on the constructor object to generate an object, which is equipped with an object array and this constructor method.





For example:


import java.lang.reflect.*;


import java.awt.*;





class Sampleinstance {





public static void Main (string[] args) {





Rectangle Rectangle;


Class rectangledefinition;








class[] Intargsclass = new class[] {int.class, int.class};


integer height = new Integer (12);


integer width = new Integer (34);


object[] Intargs = new object[] {height, width};





constructor Intargsconstructor;





try {


//1.


rectangledefinition = Class.forName ("Java.awt.Rectangle");


//2.


Intargsconstructor =


Rectangledefinition.getconstructor (Intargsclass);//Find the specified construction method


//3.


Rectangle =


(Rectangle) CreateObject (Intargsconstructor, Intargs);//Construction Method Description object, object[]


} catch (ClassNotFoundException e) {


System.out.println (e);


} catch (Nosuchmethodexception e) {


System.out.println (e);


}


}





public static Object CreateObject (constructor constructor,


object[] arguments) {





System.out.println ("constructor:" + constructor.tostring ());


object = null;





try {


object = constructor.newinstance (arguments);


System.out.println ("Object:" + object.tostring ());


return object;


} catch (Instantiationexception e) {


System.out.println (e);


} catch (Illegalaccessexception e) {


System.out.println (e);


catch (IllegalArgumentException e) {


System.out.println (e);


} catch (InvocationTargetException e) {


System.out.println (e);


}


return object;


}


}











2. Getting Field Values


If You are are writing a development tool such as a debugger, you are must to able field values. This is a three-step process:


if you want to make a development tool like debugger, you must be able to discover filed values, here are three steps:


A. Create a Class object


B. Create a Field object by GetField


c. Call Field.getxxx (object) method (XXX is int,float, if the object is omitted; object is the real


case).





For example:


import java.lang.reflect.*;


import java.awt.*;





class Sampleget {





public static void Main (string[] args) {


Rectangle r = new Rectangle (100, 325);


Printheight (R);





}





static void Printheight (Rectangle r) {


Field Heightfield;


Integer Heightvalue;


Class C = R.getclass ();


try {


Heightfield = C.getfield ("height");


Heightvalue = (Integer) heightfield.get (R);


System.out.println ("Height:" + heightvalue.tostring ());


} catch (Nosuchfieldexception e) {


System.out.println (e);


} catch (SecurityException e) {


System.out.println (e);


} catch (Illegalaccessexception e) {


System.out.println (e);


}


}


}





3. Setting Field Values


A. Create a Class object


B. Create a Field object by GetField


c. Call the Field.set (Object,withparam) method (XXX is int,float, if the object is omitted; object is an instance, Withparam refers to a field that matches this field.)





Import java.lang.reflect.*;


import java.awt.*;





class Sampleset {





public static void Main (string[] args) {


Rectangle r = new Rectangle (100, 20);


System.out.println ("Original:" + r.tostring ());


Modifywidth (R, New Integer (300));


System.out.println ("Modified:" + r.tostring ());


}





static void Modifywidth (Rectangle R, Integer widthparam) {


Field Widthfield;


Integer Widthvalue;


Class C = R.getclass ();


try {


Widthfield = C.getfield ("width");


Widthfield.set (R, Widthparam);


} catch (Nosuchfieldexception e) {


System.out.println (e);


} catch (Illegalaccessexception e) {


System.out.println (e);


}


}


}





4. Invokes the specified method


A. Create a Class object


B. Create a Method object Method,getmethod (String methodname,class[]) method


C. Method Object, Method.invoke (object,object[]), two parameters, the first refers to the object to which the method is invoked, and the second is the list of Value objects passed.





the "sample program" that follows shows and you to invoke a method dynamically. The program retrieves the "method object" String.Concat method and then uses invoke to concatenate two String object S.


//








import java.lang.reflect.*;





class Sampleinvoke {





public static void Main (string[] args) {


String FirstWord = "Hello"; Specify an instance of the class





String Secondword = "everybody."; /meta








String bothwords = append (FirstWord, Secondword);


System.out.println (bothwords);


}





public static string append (String FirstWord, String secondword) {


String result = null;


Class C = string.class;


class[] parametertypes = new class[] {string.class};


method Concatmethod;


object[] arguments = new object[] {Secondword};


try {


Concatmethod = C.getmethod ("Concat", parametertypes);//Get to Method object


result = (String) concatmethod.invoke (FirstWord, arguments);//Call


} catch (Nosuchmethodexception e) {


System.out.println (e);


} catch (Illegalaccessexception e) {


System.out.println (e);


} catch (InvocationTargetException e) {


System.out.println (e);


}


return result;


}


}

















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.