Java replaces the value in English letters under the condition of using reflection

  • 2021-07-13 05:19:48
  • OfStack

Java replaces the value in English letters under the condition of using reflection

(1) Create two Classs:

The ReflectTest classes are as follows:


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){ // Same as 1 Equal sign for bytecodes   Instead of using equal
  String oldValue = (String) field.get(obj);
  String newValue = oldValue.replace('b','a');
  field.set(obj, newValue);
  }
 } 
 } 
}

The ReflectPoint classes are as follows:


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
 }
}

The results were as follows: aall: aasketaall: itcast

Summarize


Related articles: