java基础加强_java基础加强

这篇博客详细介绍了Java中的反射机制,包括通过类名、实例和Class.forName获取类的字节码,以及如何利用反射操作构造方法、成员变量和方法。示例代码展示了如何改变对象的成员变量值、调用方法以及加载配置文件。此外,还涉及到了类加载器加载资源文件的方法。
摘要由CSDN通过智能技术生成

获取一个类的字节码有三种方法:A、知道类名:类名.class;B、有类的实例p,那么p.getClass();C、基本数据类型装载并且返回字节码:Class.forName("java.lang.String");

总之,只要是在源程序中出现的类型都有Class示例对象。比如:int

A、构造方法反射

获取一个类的所有构造方法:Constructor[] constructor = String.class.getConstructors();

获取一个类里面指定的构造方法:Constructor constructor = String.class.getConstructor(StringBuffer.class);括号内使用了可变参数

String str = constructor.newInstance(new StringBuffer("abc"));

B、成员变量反射(将一个类的String类型成员变量值里面的a换成b)

ReflectPoint point = new ReflectPoint(3,5);

Field[] fields = point.getClass.getFields();

for(Field field:fields){

if(field.getType()==String.class){}

String oldValue =(String) field.get(point);

String newValue = oldValue.replace('a','b');

field.set(point,newValue);

}

C、成员方法反射

Method method = String.class.getMethod("charAt",int.class);

System.out.println(method.invoke(str1,1));                                     //invoke方法是调用方法对象的方法。假如str1对应的是null,那么调用的是静态方法

package com.day1;

import java.io.FileInputStream; import java.io.InputStream; import java.util.Collection; import java.util.Properties; public class ReflectTest {  public static void main(String[] args) throws Exception {   //web开发基本用的是这个,eclipse自动将classpath下的文件自动按照目录结构添加到java的.class文件夹下   /**    * 使用类加载器加载配置文件    */   InputStream ips0 = ReflectTest.class.getClassLoader().getResourceAsStream("config.properties");   /**    * 对于自己这个类来说    *   相对路径,不加/    *   绝对路径,加/    */   //相对于本类的路径来说   InputStream ips1 = ReflectTest.class.getResourceAsStream("sources/config.properties");   //相对于本类的绝对路径来说   InputStream ips2 = ReflectTest.class.getResourceAsStream("/com/day1/sources/config.properties");      //如果需要保存的话,就用这种方式   InputStream ips = new FileInputStream("config.properties");   //InputStream ips = new FileInputStream("src/config.properties");   Properties props = new Properties();   props.load(ips);   ips.close();      String className = props.getProperty("className");   Collection col = (Collection)Class.forName(className).newInstance();   ReflectPoint point1 = new ReflectPoint(3, 3);   ReflectPoint point2 = new ReflectPoint(3, 5);   ReflectPoint point3 = new ReflectPoint(3, 3);   //Collection col = new HashSet();   col.add(point1);   col.add(point2);   col.add(point3);   point1.y = 7;   col.remove(point1);//其实没有除掉,内存泄露   System.out.println(col.size());  } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值