Skip to content

Commit 2df09cf

Browse files
committed
add TypeToken<T> to get a T's type in face of type erasure
1 parent a5fa9c9 commit 2df09cf

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of Swift.org project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
package org.swift.swiftkit.util;
16+
17+
import java.lang.reflect.ParameterizedType;
18+
import java.lang.reflect.Type;
19+
20+
/**
21+
* Type token to obtain the underlying {@link Type} of a generic type {@code T}.
22+
* @param <T>
23+
*/
24+
public abstract class TypeToken<T> {
25+
private Type type;
26+
27+
protected TypeToken(){
28+
Type superClass = getClass().getGenericSuperclass();
29+
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
30+
}
31+
32+
public Type getType() {
33+
return type;
34+
}
35+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of Swift.org project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
package org.swift.swiftkit.util;
16+
17+
import org.junit.jupiter.api.Test;
18+
19+
import java.lang.reflect.Type;
20+
21+
import static org.junit.jupiter.api.Assertions.*;
22+
23+
class TypeTokenTest {
24+
@Test
25+
void token() {
26+
var token = new TypeToken<String>() {};
27+
Type type = token.getType();
28+
assertEquals(String.class, type);
29+
}
30+
}

0 commit comments

Comments
 (0)