Java 通过反射提取泛型类型的实际类型

huangapple 未分类评论57阅读模式
标题翻译

Java Extract real type of Generic type by reflexion

问题

我希望在保存数据之前根据ID的实际类型String UUID或随机Long生成两种类型的ID

@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> {
}

在我的服务实现中我尝试过以下方法

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


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();
}

> 期望值是String或Long但实际获取的始终是Object
英文翻译

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&lt;ID&gt; implements Serializable { 
    @Id protected ID id;
  }

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

@Repository
public interface SoftwareRepository extends JpaRepository&lt;Software, String&gt; {
}

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

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

and

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

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

Thanks

huangapple
  • 本文由 发表于 2020年3月16日 20:41:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/60706220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定