Integer Type Reference String Value

two classes:

public class BaseDo<K> {
    protected K id;

    public K getId() {
        return id;
    }

    public void setId(K id) {
        this.id = id;
    }
}


public class BeanDo extends BaseDo<Integer> {
    private String beanName;

    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }
}

I want to use reflect to implement like this:

BeanDo beanDo = new BeanDo();
beanDo.setId("string here");

Integer reference to the type. Value of type String.

+3
source share
5 answers

Generics in Java are not used at runtime, because at java runtime you are an identifier field of type Object and therefore can be set to any value regardless of generics. However, this is a bad idea, since everything that assumes that the general contract will not work.

You can set the field by reflection as follows:

BeanDo beanDo = new BeanDo();
Method method = BeanDo.getClass().getMethod("setId", Object.class);
method.invoke(beanDo, "SomeRandomString");

, , BeanDo , id , . , , beanDo.getId(), cast, .

, , .

+1

- ?

public class BaseDo<K> {

  protected K id;

  public K getId() {
    return id;
  }

  public void setId(K id) {
    this.id = id;
  }

}

public class BeanDo extends BaseDo<Integer> { 

  private String beanName;

  public void setId(String id) {
    setId(Integer.parseInt(id));
  }

  public String getBeanName() {
    return beanName;
  }

  public void setBeanName(String beanName) {
    this.beanName = beanName;
  }

}

- :

BeanDo beanDo = new BeanDo();
beanDo.setId("2");
0

:

BeanDo beando = new BeanDo();
beando.setId("string there".hashCode());

, : " ".

, - :

    BeanDo doer = ... // get it from somewhere
    String id   = ... // get it from somewhere else too. 

    // and you want to set id to the doer bean.
    reflectionMagicSetId( doer, id ); 

:

 private void reflectionMagicSetId( BandDo doer, String id ) {
       /// do some magic here? 
 }

, , , , .

 private void reflectionMagicSetId( BandDo doer, String id ) {
     doer.setId( id == null ? 0 : id.hashCode()  );
 }
0

wann , ,

0

, , , , getId(), Integer, . - :

public class StringBeanDo extends BeanDo {
  private String stringId;

  public String getStringId()
  {
    return stringId;
  }

  public void setId( Integer val )
  {
    super.setId( val );
    stringId = Integer.toString( val );
  }

  public void setId( String str )
  {
    stringId = str;
    super.setId( convertStringToInteger( str )); // Do this however you like.
  }
}

The implementation convertStringToIntegerwill be up to you (this will depend on what this identifier is used for). The key point here is that you maintain TWO ID and keep them in sync so that the old code can still be lame to some extent.

0
source

Source: https://habr.com/ru/post/1751496/


All Articles