在本教程中,我主要编写一些示例来介绍Java反射可以做什么。 希望它可以给您这个概念的概述。 请留下您的评论以寻求建议。
什么是反射?
简而言之,反射是程序在运行时检查和修改对象的结构和行为的能力。
这种概念有时与内省混合在一起。 自省(类型自省)是程序在运行时检查对象的类型或属性的能力。 因此,它是反射的子集。 某些语言支持自省,但不支持反射,例如C ++。
为什么我们需要反思?
反射使我们能够执行以下操作:
- 在运行时检查对象的类
- 在运行时为类构造一个对象
- 在运行时检查类的字段和方法
- 在运行时调用对象的任何方法
例如, JUnit使用反射来查看带有@Test批注的方法,然后在运行单元测试时调用这些方法。 (这是一组有关如何使用JUnit的示例。)
示例1:从对象获取类名
package myreflection;
import java.lang.reflect.Method;
public class ReflectionHelloWorld {
public static void main(String[] args){
Foo f = new Foo();
System.out.println(f.getClass().getName());
}
}
class Foo {
public void print() {
System.out.println("abc");
}
}
输出:
myreflection.Foo
示例2:对未知对象调用方法
对于下面的代码示例,未知对象的图像类型。 通过使用反射,代码可以使用该对象并找出该对象是否具有称为“ print”的方法,然后对其进行调用。
package myreflection;
import java.lang.reflect.Method;
public class ReflectionHelloWorld {
public static void main(String[] args){
Foo f = new Foo();
Method method;
try {
method = f.getClass().getMethod("print", new Class<?>[0]);
method.invoke(f);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Foo {
public void print() {
System.out.println("abc");
}
}
abc
示例3:从Class实例创建对象
package myreflection;
public class ReflectionHelloWorld {
public static void main(String[] args){
//create instance of "Class"
Class<?> c = null;
try{
c=Class.forName("myreflection.Foo");
}catch(Exception e){
e.printStackTrace();
}
//create instance of "Foo"
Foo f = null;
try {
f = (Foo) c.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
f.print();
}
}
class Foo {
public void print() {
System.out.println("abc");
}
}
示例4:获取构造函数并创建实例
package myreflection;
import java.lang.reflect.Constructor;
public class ReflectionHelloWorld {
public static void main(String[] args){
//create instance of "Class"
Class<?> c = null;
try{
c=Class.forName("myreflection.Foo");
}catch(Exception e){
e.printStackTrace();
}
//create instance of "Foo"
Foo f1 = null;
Foo f2 = null;
//get all constructors
Constructor<?> cons[] = c.getConstructors();
try {
f1 = (Foo) cons[0].newInstance();
f2 = (Foo) cons[1].newInstance("abc");
} catch (Exception e) {
e.printStackTrace();
}
f1.print();
f2.print();
}
}
class Foo {
String s;
public Foo(){}
public Foo(String s){
this.s=s;
}
public void print() {
System.out.println(s);
}
}
输出:
null
abc
此外,您可以使用Class实例获取已实现的接口,超类,声明的字段等。
示例5:通过反射更改数组大小
package myreflection;
import java.lang.reflect.Array;
public class ReflectionHelloWorld {
public static void main(String[] args) {
int[] intArray = { 1, 2, 3, 4, 5 };
int[] newIntArray = (int[]) changeArraySize(intArray, 10);
print(newIntArray);
String[] atr = { "a", "b", "c", "d", "e" };
String[] str1 = (String[]) changeArraySize(atr, 10);
print(str1);
}
// change array size
public static Object changeArraySize(Object obj, int len) {
Class<?> arr = obj.getClass().getComponentType();
Object newArray = Array.newInstance(arr, len);
//do array copy
int co = Array.getLength(obj);
System.arraycopy(obj, 0, newArray, 0, co);
return newArray;
}
// print
public static void print(Object obj) {
Class<?> c = obj.getClass();
if (!c.isArray()) {
return;
}
System.out.println("\nArray length: " + Array.getLength(obj));
for (int i = 0; i < Array.getLength(obj); i++) {
System.out.print(Array.get(obj, i) + " ");
}
}
}
输出:
Array length: 10
1 2 3 4 5 0 0 0 0 0
Array length: 10
a b c d e null null null null null
摘要
上面的代码示例显示了Java反射提供的一小组功能。 阅读这些示例可能只会使您对Java有所了解 ,您可能想阅读Oracle网站上的更多信息 。
翻译自: https://www.javacodegeeks.com/2013/09/java-reflection-tutorial.html