Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type passing and usage, can I do the following?

I try to figure out how I can access a static method within CallMe<T>() of class DoSomething. Is reflection the only solution here? I do not want to instantiate an object of type MyAction. Also if doing it through reflection is there a way to create the method through reflection within the method CallMe<T>() just once and then calling it many times to perform multiple operations on the same "reflected" method? Or is there any better way than through reflection? I basically want to create template implementation style classes such as MyAction that define how byte[] DoThis(string text) performs its duty. The AskForSomething() will then specify which template is being used and according to that the CallMe<T>() will go about its work.

    public class AskSomething
    {
        public void AskForSomething()
        {
            DoSomething doSomething = new DoSomething();
            doSomething.CallMe<MyAction>();
        }
    }

    public class DoSomething
    {
        public void CallMe<T>()
        {
            Type type = typeof(T);

            //Question: How can I access 'DoThis(string text)' here?
            //Most likely by reflection? 
        }
    }

    public class MyAction
    {
        public static byte[] DoThis(string text)
        {
            byte[] ret = new byte[0]; //mock just to denote something is done and out comes a byte array

            return ret;
        }
    }
like image 278
Matt Avatar asked Dec 21 '12 12:12

Matt


People also ask

What are generic types used for?

Generics overview Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes.

How do you pass a generic object in Java?

Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);

Can you give an example of a generic method?

Example: Create a Generics Method Here, the type parameter <T> is inserted after the modifier public and before the return type void . We can call the generics method by placing the actual type <String> and <Integer> inside the bracket before the method name. demo. <String>genericMethod("Java Programming"); demo.

Which one of the following construct is used to create generic classes or methods?

We use <T> to create a generic class, interface, and method. The T is replaced with the actual type when we use it.


1 Answers

Define an interface with DoThis, have MyAction implement it, and constrain the T type parameter to be an instance of it with where T : IMyInterface

like image 194
Kieren Johnstone Avatar answered Oct 07 '22 02:10

Kieren Johnstone