标题翻译
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<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
专注分享java语言的经验与见解,让所有开发者获益!
评论