Is it possible to create a generic method of type T
where T
has a specific attribute?
E.g.:
public static XmlDocument SerializeObjectToXml<T>(T obj)
{
//...
}
and I want to serialize only a classes with a Serializable
and/or DataContract
attribute:
[Serializable]
[DataContract(Name = "viewModel", Namespace = "ns")]
internal class ViewModel
{
//...
}
Generic attributes are qualities, skills, and abilities that are valued in study, social situations and employment. They include problem solving ability, teamwork, critical thinking, self-management and basic numeracy.
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.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Perhaps you can do it indirectly, by creating a base-class which has the Serializable attribute, and add a constraint to your generic class, so that the type-parameter should inherit from that base-class:
[Serializable]
public class MyBase {}
public static XmlDocument SerializeToXml<T>( T obj ) where T : MyBase {}
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