JAVA反射技术(二)
类别: JAVA教程
Lesson:2 处理对象
1.Creating Objects
一般情况下,创建一个对象用以下方法
Rectangle r = new Rectangle();
但如果你正在开发一个development tools,在运行之前或许不知道要生成对象的类。
所以要像下面这样来创建对象:
String className;
// . . . load className from the user interface
Object o = new (className); // WRONG!
但以上是错误的。
正确的方法是使用类的反射特性:
1)Using No-Argument Constructors
例如:
Class classDefinition = Class.forName(className);//指定类的运行期实例
object = classDefinition.newInstance();//调用无参构造函数来生成指定类的实例。
2)Using Constructors that Have Arguments
这个技术要用到如下步骤:
a,创建一个Class对象
b,创建一个Constructor对象,getConstructor(Class[] params)方法,参数是一个与构造方法相适合的Class 数组.
c,在Constructor对象上调用newInstance方法来生成一个对象,参数 是一个object数组与这个构造方法相配备。
例如:
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);//找到指定的构造方法
//3.
rectangle =
(Rectangle) createObject(intArgsConstructor, intArgs);//构造方法描述对象,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 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 writing a development tool such as a debugger, you must be able to obtain field values. This is a three-step process:
如果要作一个开发工具像debugger之类的,你必须能发现filed values,以下是三个步骤:
a.创建一个Class对象
b.通过getField 创建一个Field对象
c.调用Field.getXXX(Object)方法(XXX是Int,Float等,如果是对象就省略;Object是指实
例).
例如:
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.创建一个Class对象
b.通过getField 创建一个Field对象
c.调用Field.set(Object,withparam)方法(XXX是Int,Float等,如果是对象就省略;Object是指实例,withparam指和这个字段相区配的字段。
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。调用指定的方法
a.创建一个Class对象
b.创建一个方法对象method,getMethod(String methodName,Class[])方法
c.调方法对象,method.invoke(object,Object[]),两个参数,第一个是指调用方法所属于的对象,第二个是传递的值对象列表。
The sample program that follows shows you how to invoke a method dynamically. The program retrieves the Method object for the String.concat method and then uses invoke to concatenate two String objects.
//
import java.lang.reflect.*;
class SampleInvoke {
public static void main(String[] args) {
String firstWord = "Hello "; //指定类的实例
String secondWord = "everybody.";//变元
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);//获取到方法对象
result = (String) concatMethod.invoke(firstWord, arguments);//调用
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
}
return result;
}
}
1.Creating Objects
一般情况下,创建一个对象用以下方法
Rectangle r = new Rectangle();
但如果你正在开发一个development tools,在运行之前或许不知道要生成对象的类。
所以要像下面这样来创建对象:
String className;
// . . . load className from the user interface
Object o = new (className); // WRONG!
但以上是错误的。
正确的方法是使用类的反射特性:
1)Using No-Argument Constructors
例如:
Class classDefinition = Class.forName(className);//指定类的运行期实例
object = classDefinition.newInstance();//调用无参构造函数来生成指定类的实例。
2)Using Constructors that Have Arguments
这个技术要用到如下步骤:
a,创建一个Class对象
b,创建一个Constructor对象,getConstructor(Class[] params)方法,参数是一个与构造方法相适合的Class 数组.
c,在Constructor对象上调用newInstance方法来生成一个对象,参数 是一个object数组与这个构造方法相配备。
例如:
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);//找到指定的构造方法
//3.
rectangle =
(Rectangle) createObject(intArgsConstructor, intArgs);//构造方法描述对象,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 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 writing a development tool such as a debugger, you must be able to obtain field values. This is a three-step process:
如果要作一个开发工具像debugger之类的,你必须能发现filed values,以下是三个步骤:
a.创建一个Class对象
b.通过getField 创建一个Field对象
c.调用Field.getXXX(Object)方法(XXX是Int,Float等,如果是对象就省略;Object是指实
例).
例如:
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.创建一个Class对象
b.通过getField 创建一个Field对象
c.调用Field.set(Object,withparam)方法(XXX是Int,Float等,如果是对象就省略;Object是指实例,withparam指和这个字段相区配的字段。
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。调用指定的方法
a.创建一个Class对象
b.创建一个方法对象method,getMethod(String methodName,Class[])方法
c.调方法对象,method.invoke(object,Object[]),两个参数,第一个是指调用方法所属于的对象,第二个是传递的值对象列表。
The sample program that follows shows you how to invoke a method dynamically. The program retrieves the Method object for the String.concat method and then uses invoke to concatenate two String objects.
//
import java.lang.reflect.*;
class SampleInvoke {
public static void main(String[] args) {
String firstWord = "Hello "; //指定类的实例
String secondWord = "everybody.";//变元
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);//获取到方法对象
result = (String) concatMethod.invoke(firstWord, arguments);//调用
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
}
return result;
}
}
- 上一篇: java反射技术(一)
- 下一篇: Java变量类型间的相互转换
-= 资 源 教 程 =-
文 章 搜 索