mercredi 1 mai 2019

Set interface field value with reflection

I wanna set field of a class. This field is an interface and i know only type at runtime not compile time. So i can't cast directly. I tried to get value and set i couldn't do.

I tried to Class.forname but when i call newIntsance getting error bcs interface don't have an constructor.

I tried to cast to child class but this time i got cast exception.

field.setAccessible(true);
Object obj = field.get(field.getType().newInstance());
Caused by: java.lang.NoSuchMethodException: com.bank.accounting.dao.DenemeDao.<init> ()


Object obj = annotatedFieldModel.getField().get(childclass.newInstance());


java.lang.IllegalArgumentException: Can not set com.bank.accounting.dao.DenemeDao field com.bank.accounting.service.MoneyTransferService.denemeDao to com.bank.accounting.dao.impl.DenemeDaoImpl
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)





Aucun commentaire:

Enregistrer un commentaire