Java Extract real type of Generic type by reflexion

Viewed 47

I'd like to generate two types of Id before saving data according to the real type of the ID (String UUID or Random Long)

  @Data
  @MappedSuperclass      
  public abstract class CommonEntity<ID> implements Serializable { 
    @Id protected ID id;
  }

@Data
@Entity
public class Software extends CommonEntity<String> implements Serializable {
    @Column(unique = true)
    private String name;
}

@Repository
public interface SoftwareRepository extends JpaRepository<Software, String> {
}

In my service implementation, I've tried something like:

Class<?> aClass = entity.getClass();
try {
Field fieldId = aClass.getSuperclass().getDeclaredField("id");
fieldId.setAccessible(true);
Type typeId = fieldId.getType();
log.info("----------Id type ----------{}", typeId);
} catch (NoSuchFieldException e) {
     e.printStackTrace();
}

and

Class<?> aClass = entity.getClass();            
        try {
            Field fieldId = aClass.getSuperclass().getDeclaredField("id");
            fieldId.setAccessible(true);
            String idTypes = fieldId.getType().getSimpleName();
            log.info("----------------------------------------------{}", idTypes);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

My expected value is String or Long. What I get is always an Object

Thanks

0 Answers
Related