3

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

JAR
  • 754
  • 4
  • 11
  • 1
    You can check that Object with String Class with **instanceof** keyword. May this will help you. – Thakkar Darshan Mar 16 '20 at 12:43
  • Maybe [this](https://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t) answerts your question – Jens Mar 16 '20 at 12:49
  • 1
    You cannot get that on runtime (as a general case) with reflection as all generic types are erased to `Object` https://docs.oracle.com/javase/tutorial/java/generics/erasure.html – Antoniossss Mar 16 '20 at 12:49
  • 1
    But this might help in your case https://stackoverflow.com/a/9202329/1527544 since you are using generic supertype – Antoniossss Mar 16 '20 at 12:52

0 Answers0