I got a generic Interface like this :
public interface IResourceDataType<T>
{
void SetResourceValue(T resValue);
}
Then I got this class that implements my Interface :
public class MyFont : IResourceDataType<System.Drawing.Font>
{
//Ctor + SetResourceValue + ...
}
And finally I got a :
var MyType = typeof(MyFont);
I, now, want to get the System.Drawing.Font
Type from MyType !
At the moment, I got this code :
if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
//If test is OK
}
But I don't manage to "extract" my Type here...
I tried a couple of things with GetGenericArguments()
and other things but they either don't compile or return a null value/List...
What do I have to do ?
EDIT : Here is the solution that fit my code for those who will get the same problem :
if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
foreach (Type type in MyType.GetInterfaces())
{
if (type.IsGenericType)
Type genericType = type.GetGenericArguments()[0];
}
}
}
Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
Generic types and methods are the defining new feature of Java 5.0. A generic type is defined using one or more type variables and has one or more methods that use a type variable as a placeholder for an argument or return type. For example, the type java. util.
Since your MyFont
class only implements one interface, you can write:
Type myType = typeof(MyFont).GetInterfaces()[0].GetGenericArguments()[0];
If your class implements several interfaces, you can call the GetInterface() method with the mangled name of the interface you're looking for:
Type myType = typeof(MyFont).GetInterface("IResourceDataType`1")
.GetGenericArguments()[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With