java利用反射替换值 Java在利用反射条件下替换英文字母中的值

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java利用反射替换值 Java在利用反射条件下替换英文字母中的值

徐刘根   2021-03-30 我要评论

Java在利用反射条件下替换英文字母中的值

(1)创建两个Class:

ReflectTest类如下:

package cn.itcast.day01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectTest {
 public static void main(String[] args) throws Exception {
 changeStringValue(pt1);
 System.out.println(pt1);
 } 
 private 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){ //同一个字节码用等号 而不是用equal
  String oldValue = (String) field.get(obj);
  String newValue = oldValue.replace('b','a');
  field.set(obj, newValue);
  }
 } 
 } 
}

ReflectPoint类如下:

package cn.itcast.day01;
public class ReflectPoint {
 public String str1 = "ball";
 public String str2 = "basketball";
 public String str3 = "itcast";
 public ReflectPoint(int x, int y) {
 super();
 this.x = x;
 this.y = y;
 }
 public String toString(){
 return str1+":"+str2+":"+str3;
 }
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 }
}

结果为:aall:aasketaall:itcast

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们