基础加强—03—反射(Reflect)

 

Person p1 = new Perosn();

Perosn p2 = new Perosn();

 

Class cls1 = Date.class //Date类的字节码

Class cls2 = Person.class //Person类的字节码

p1.getClass(); //通过对象得到Person类的字节码

Class.forName(“java.lang.String”) //返回字节码。

 

第一种情况:这个字节码以前加载过,还呆在java虚拟机中,可以直接返回。

第二种情况:java虚拟机中还没有加载,这时java虚拟机就会加载,放在缓冲区后,返回字节码。

8个基本类型和一个void类型:boolean  byte  char  short  int  long  float  double

public class ReflectTest {
	public static void main(String[] args) throws Exception{
		String str1 = "abc";
		Class cls1 = str1.getClass();
		Class cls2 = String.class;
		Class cls3 = Class.forName("java.lang.String");
		System.out.println(cls1 == cls2);//true
		System.out.println(cls1 == cls3);//true
		
		System.out.println(cls1.isPrimitive());//cls1不是基本类型
		System.out.println(int.class.isPrimitive());//int是基本类型
		System.out.println(int.class == Integer.class);//flase
		System.out.println(int.class == Integer.TYPE);//true
		System.out.println(int[].class.isPrimitive());//flase,数组不是基本类型
		System.out.println(int[].class.isArray());//true,数组有Class实例对象
	}
}


import java.lang.reflect.Constructor;

public class ReflectTest {
	public static void main(String[] args) throws Exception{
		//new String(new StringBuffer("abc"))
		//定义泛型<String>,调用获得的方法时要用到上面相同类型的实例对象
		Constructor<String> c1 = String.class.getConstructor(StringBuffer.class);
		String str2 = c1.newInstance(new StringBuffer("abc"));
		System.out.println(str2.charAt(2));
	}
}

public class ReflectPoint {
	private int x;
	public int y;
	public ReflectPoint(int x, int y) {//生成构造方法
		super();
		this.x = x;
		this.y = y;
	}
}
import java.lang.reflect.Field;
public class ReflectTest {
	public static void main(String[] args) throws Exception{
		ReflectPoint pt1 = new ReflectPoint(3,5);//创建对象,传入参数
		Field fieldY = pt1.getClass().getField("y");//获取pt1对应的字节码对象,并获取变量y
		//fieldY的值是多少啊?是5,错
		//fieldY不是对象身上的变量,而是类上,要用它去取某个对象上对应的值
		System.out.println(fieldY.get(pt1));//输出5
		
		Field fieldX = pt1.getClass().getDeclaredField("x");//获取私有变量x的字节码对象
		fieldX.setAccessible(true);//可以获取私有变量的值了,即暴力反射
		System.out.println(fieldX.get(pt1));//输出3
	}
}

public class ReflectPoint {
	public String str1 = "ball";
	public String str2 = "basketball";
	public String str3 = "itcast";
	@Override
	public String toString() {
		return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
				+ str3 + "];

 

import java.lang.reflect.Field;

public class ReflectTest {
	public static void main(String[] args) throws Exception{
		ReflectPoint pt1 = new ReflectPoint();
		changeStringValue(pt1);
		System.out.println(pt1);
	}
	
	public static void changeStringValue(Object obj)throws Exception{
		Field[] fields = obj.getClass().getFields();//得到所属的字节码,再得到字段
		for(Field field : fields){
			//if(field.getType().equals(String.class));对于字节码,要用==比
			if(field.getType() == String.class){//得到字段所属的类型,并比较是不是 String类型的字节码
				String oldValue = (String)field.get(obj);
				String newValue = oldValue.replace('b', 'a');
				field.set(obj,newValue);
			}
		}
	}
}


import java.lang.reflect.Method;

public class ReflectTest {
	public static void main(String[] args) throws Exception{
		String str1 = "abc";
		//str1.charAt(1),用反射的方式获取String的字节码中的方法,再用方法作用于某个对象
		Method methodCharAt = String.class.getMethod("charAt", int.class);
		System.out.println(methodCharAt.invoke(str1, 1));//输出b
		System.out.println(methodCharAt.invoke(str1,new Object[]{2}));//输出c,JDK1.4写法
	}
}	


 

import java.lang.reflect.Method;

public class test {
	static void main(String[] args) throws Exception {
		//TestArguments1.main(new String[]{"111","222","333"});
		String startingClassName = args[0];
		Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);
		//mainMethod.invoke(null,new Object[]{new String[]{"111","222","333"}});//main是静态方法,不需要传递参数
		mainMethod.invoke(null,(Object)new String[]{"111","222","333"});//main是静态方法,不需要传递参数
	}
}
class TestArguments1{
	public static void main(String[] args){
		for(String arg : args){
			System.out.println(arg);
		}
	}
}


*怎么得到数组中的元素类型?
例:int[] a = new int[3];
怎么知道是int型的?
Object[] a = new Object[]("a",1)
a[0].getClass().getName();//只能获取数组中具体的元素类型

import java.util.Arrays;

public class test {
	static void main(String[] args) throws Exception {
		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());//true
		//System.out.println(a1.getClass() == a4.getClass());//false
		//System.out.println(a1.getClass() == a3.getClass());//false
		System.out.println(a1.getClass().getName());//获取字节码名称 [I
		System.out.println(a1.getClass().getSuperclass());//输出父类的名称class java.lang.Object
		System.out.println(a4.getClass().getSuperclass());//输出父类的名称class java.lang.Object
		
		Object aObj1 = a1;
		Object aObj2 = a4;
		//Object[] aObj3 = a1;//错误
		Object[] aObj4 = a3;
		Object[] aObj5 = a4;
		
		System.out.println(a1);//输出[I@1f33675
		System.out.println(a4);//输出[Ljava.lang.String;@7c6768
		System.out.println(Arrays.asList(a1));//[[I@1f33675],整数不行
		System.out.println(Arrays.asList(a4));//字符变成List集合输出[a, b, c]
	}
}
import java.lang.reflect.Array;

public class test {
	static void main(String[] args) throws Exception {
		int[] a1 = new int[]{1,2,3};
		String[] a4 = new String[]{"a","b","c"};
		
		printObject(a1);
		printObject(a4);
		printObject("xyz");
	}
	private static void printObject(Object obj) {
		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);
		}
	}
}


public class ReflectTest2 {
	public static void main(String[] args)throws Exception {
		//一定要记住用完整的路径,但是完整的路径不是硬编码,而是运算出来的
		//InputStream ips = new FileInputStream("config.properties");
		
		//通过ReflectTest2找类,再通过类去找类加载器
		//InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");;
		//InputStream ips = ReflectTest2.class.getResourceAsStream("config.properties");;
		InputStream ips = ReflectTest2.class.getResourceAsStream("resource/config.properties");;

		
		Properties props = new Properties();//创建系统信息对象
		props.load(ips);//将文件中的内容加载到系统
		ips.close();
		String className = props.getProperty("className");//通过键获取系统信息
		//通过类获取实例对象
		Collection collections = (Collection)Class.forName(className).newInstance();
		
		ReflectPoint pt1 = new ReflectPoint(3,3);
		ReflectPoint pt2 = new ReflectPoint(5,5);
		ReflectPoint pt3 = new ReflectPoint(3,3);
		
		collections.add(pt1);
		collections.add(pt2);
		collections.add(pt3);
		collections.add(pt1);

		System.out.println(collections.size());
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值