mercredi 22 août 2018

How to get processed object and set it a new value to it in Java via Reflection API?

I was searching and learning Java Reflection API more about it. But I could not find some part of my problem's solution in it. The problem is, I want to change just one feature of my object. Here is code;

    public class Car{
          private String model_name;
          private int horsepower;
          public Tire t;

          public void setModelName(String s){
              model_name = s;
          }

          public void setHorsePower(int i){
              horsepower = i;
          }

          public String getModelName(){
              return model_name;
          }

          public int getHorsePower(){
              return horsepower;
          }
    }

    // Tire.java

    public class Tire{
          private String name;

          public void setName(String s){
              name = s;
          }

          public String getName(){
              return name;
          }
    }

    // Main class

    public class Main{
       public static void main(String []args){
           Car a = new Car();
           a.setModelName("Mustang 67");
           a.setHorsePower(700);
           a.t = new Tire("DummyBrand");
           Class c = a.getClass();
           Field []f = c.getDeclaredFields();
           for(int i = 0; i < f.length; i++){
               if(f[i].getType().getSimpleName().toString().matches("Tire"){
                   // How to change a object's t field's name variable? 
               }
           }
           System.out.printline(a.getModelName)   
       }
    }

I would be gladful if you guys and ladies can help. Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire