您的位置:首页 > 职场人生

黑马程序员——Java基础---反射

2015-06-13 13:07 627 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

基本概念

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

功能

Java 反射机制主要提供了以下功能:

在运行时判断任意一个对象所属的类。

在运行时构造任意一个类的对象。

在运行时判断任意一个类所具有的成员变量和方法。

在运行时调用任意一个对象的方法。

Class类:代表一个类。

Field 类:代表类的成员变量(成员变量也称为类的属性)。

Method类:代表类的方法。

Constructor 类:代表类的构造方法。

Array类:提供了动态创建数组,以及访问数组的元素的静态方法。

方法

getName():获得类的完整名字。

getFields():获得类的public类型的属性。

getDeclaredFields():获得类的所有属性。

getMethods():获得类的public类型的方法。

getDeclaredMethods():获得类的所有方法。

getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。

getConstructors():获得类的public类型的构造方法。

getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。

newInstance():通过类的不带参数的构造方法创建这个类的一个对象。

反射代码示例:

package net.itcast.day1;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectTest {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String str1 = "abc";
Class<?> cls1 = str1.getClass();
Class<?> cls2 = String.class;
Class<?> cls3 = Class.forName("java.lang.String");
System.out.println(cls1);
System.out.println(cls1 == cls2);
System.out.println(cls1 == cls3);

System.out.println(cls1.isPrimitive());
System.out.println(int.class == Integer.class);
System.out.println(int.class == Integer.TYPE);
System.out.println(int[].class.isPrimitive());
System.out.println(int[].class.isArray());

// new String(new StringBuffer("abc"));
Constructor<?> constructor1 = String.class
.getConstructor(StringBuffer.class);
String str2 = (String) constructor1
.newInstance(new StringBuffer("abc"));
System.out.println(str2);

ReflectPoint rp1 = new ReflectPoint(3, 5);
Field fieldY = rp1.getClass().getField("y");
// fieldY的值是多少?是5,错!field不是对象身上的变量,而是类上,要用他去取某个对象上对应的值。
System.out.println(fieldY.get(rp1));
Field fieldX = rp1.getClass().getDeclaredField("x");
fieldX.setAccessible(true);
System.out.println(fieldX.get(rp1));

changeStringValue(rp1);
System.out.println(rp1);

Method methodCharAt = String.class.getMethod("charAt", int.class);
System.out.println(methodCharAt.invoke(str1, 1));
// TestArguments.main(new String[]{"111","222","333"});
String startingClassName = args[0];
Method mainMethod = Class.forName(startingClassName).getMethod("main",
String[].class);
mainMethod.invoke(null, (Object) new String[] { "111", "222", "333" });

int[] a1 = new int[] { 1, 2, 3 };
int[] a2 = new int[4];
// int[][] a3 = new int[2][3];
String[] a4 = new String[] { "a", "b", "c" };
System.out.println(a1.getClass() == a2.getClass());
System.out.println(a1.getClass().getName());
System.out.println(a1.getClass().getSuperclass().getName());
System.out.println(a4.getClass().getSuperclass().getName());

// Object a1Obj = a1;
// Object a2Obj = a2;
// Object[] a3Obj = a3;
// Object[] a4Obj = a4;
System.out.println(a1);
System.out.println(a4);
System.out.println(Arrays.asList(a1));
System.out.println(Arrays.asList(a4));

printObj(a4);
printObj("xyz");
}

private static void printObj(Object obj) {
// TODO Auto-generated method stub
Class<?> clazz = obj.getClass();
if (clazz.isArray()) {
int len = Array.getLength(obj);
for (int i = 0; i < len; i++) {
System.out.println(Array.get(obj, i));
}
} else {
System.out.println(obj);
}
}

private static void changeStringValue(Object obj) throws Exception {
// TODO Auto-generated method stub
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
if (field.getType() == String.class) {
String oldValue = (String) field.get(obj);
String newValue = oldValue.replace('b', 'a');
field.set(obj, newValue);
}
}
}
}

class TestArguments {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
package net.itcast.day1;

import java.util.Date;

public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";

public ReflectPoint(int x, int y) {
this.x = x;
this.y = y;
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

public String toString() {
return str1 + ":" + str2 + ":" + str3;
}

}

反射的作用

实现框架功能

代码示例:

package net.itcast.day1;

//import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

public class ReflectTest2 {

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// 一定要记住用完整的路径,但完整的路径不是硬编码,而是运算出来的。
// InputStream is = new FileInputStream("config.properties");
// InputStream is = ReflectTest2.class.getClassLoader()
// .getResourceAsStream("net/itcast/config.properties");
// InputStream is =
// ReflectTest2.class.getResourceAsStream("resources/config.properties");
InputStream is = ReflectTest2.class.getResourceAsStream("/net/itcast/resources/config.properties");
Properties props = new Properties();
props.load(is);
is.close();
String className = props.getProperty("className");
Collection<ReflectPoint> collection = (Collection<ReflectPoint>) C
4000
lass
.forName(className).newInstance();
// Collection collection = new HashSet();
ReflectPoint pt1 = new ReflectPoint(3, 3);
ReflectPoint pt2 = new ReflectPoint(5, 5);
ReflectPoint pt3 = new ReflectPoint(3, 3);
collection.add(pt1);
collection.add(pt2);
collection.add(pt3);
collection.add(pt1);
// pt1.y=7;
// collection.remove(pt1);
System.out.println(collection.size());
}

}

总结

反射在刚开始感觉挺难的,但是在老师细心仔细的讲解下,也理解了,反射是一种操作其他的类的一种方式,反射在很多框架上应用非常广泛。由于学习的只是一些基础,还不能理解一些复杂应用,还需要自己不断的尝试探索。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: