TypedEntityReference reducing factory methods to one
[cdmlib.git] / cdmlib-model / src / main / java / eu / etaxonomy / cdm / ref / TypedEntityReference.java
1 /**
2 * Copyright (C) 2017 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9 package eu.etaxonomy.cdm.ref;
10
11 import java.util.UUID;
12
13 import org.apache.commons.lang3.builder.HashCodeBuilder;
14
15 import eu.etaxonomy.cdm.model.common.CdmBase;
16 import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
17
18 /**
19 * @author a.kohlbecker
20 * @since Jun 12, 2017
21 *
22 */
23 public class TypedEntityReference<T extends CdmBase> extends EntityReference {
24
25 private static final long serialVersionUID = -4619590272174606288L;
26
27 private Class<T> type;
28
29 /**
30 * @param uuid
31 * @param label
32 */
33 public TypedEntityReference(Class<T> type, UUID uuid, String label) {
34 super(uuid, label);
35 this.type = type;
36 }
37
38 public TypedEntityReference(Class<T> type, UUID uuid) {
39 super(uuid, null);
40 this.type = type;
41 }
42
43 public static <T extends CdmBase> TypedEntityReference<T> fromEntity(T entity) {
44 if(entity == null) {
45 return null;
46 }
47 if(IdentifiableEntity.class.isAssignableFrom(entity.getClass())) {
48 return new TypedEntityReference<T>((Class<T>)entity.getClass(), entity.getUuid(), ((IdentifiableEntity)entity).getTitleCache());
49 } else {
50 return new TypedEntityReference<T>((Class<T>)entity.getClass(), entity.getUuid());
51 }
52 }
53
54 public Class<T> getType() {
55 return type;
56 }
57 public void setType(Class<T> type) {
58 this.type = type;
59 }
60
61 /**
62 * {@inheritDoc}
63 */
64 @Override
65 public int hashCode() {
66 return new HashCodeBuilder(17, 31)
67 .append(uuid)
68 .appendSuper(type.hashCode())
69 .hashCode();
70 }
71
72 /**
73 * {@inheritDoc}
74 */
75 @SuppressWarnings("rawtypes")
76 @Override
77 public boolean equals(Object obj) {
78 try {
79 TypedEntityReference other = (TypedEntityReference) obj;
80 return uuid.equals(other.uuid) && type.equals(other.type);
81
82 } catch (Exception e) {
83 return false;
84 }
85 }
86
87 @Override
88 public String toString(){
89 return type.getSimpleName() + "#" + uuid;
90
91 }
92
93 }