Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 2/41 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Generics and reflection in Java

    - by Ragesh
    This is probably a very basic question, but I'm really new to generics in Java and I'm having a hard time altering my thought process from the way things are done in C#, so bear with me. I'm trying to build a generic repository in Java. I've created an IRepository interface that looks like this: public interface IRepository<T extends IEntity> And a Repository class that looks like this: public class Repository<T extends IEntity> implements IRepository<T> Now, from within the constructor of my Repository class, I'd like to be able to "divine" the exact type of T. For example, if I instantiated a repository like this: IRepository<MyClass> repo = new Repository<MyClass>(); I'd like to know that T is actually MyClass. This is trivial in C#, but obviously generics are a totally different beast in Java and I can't seem to find anything that would help me do this.

    Read the article

  • Delegate.CreateDelegate() and generics: Error binding to target method

    - by SDReyes
    I'm having problems creating a collection of delegate using reflection and generics. I'm trying to create a delegate collection from Ally methods, whose share a common method signature. public class Classy { public string FirstMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); public string SecondMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); public string ThirdMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); // And so on... } And the generics cooking: // This is the Classy's shared method signature public delegate string classyDelegate<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> filter ); // And the linq-way to get the collection of delegates from Classy ( from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic ) let delegateType = typeof( classyDelegate<,> ) select Delegate.CreateDelegate( delegateType, method ) ).ToList( ); But the Delegate.CreateDelegate( delegateType, method ) throws an ArgumentException saying Error binding to target method. : / What am I doing wrong?

    Read the article

  • Generics with constraints hierarchy

    - by devoured elysium
    I am currently facing a very disturbing problem: interface IStateSpace<Position, Value> where Position : IPosition // <-- Problem starts here where Value : IValue // <-- and here as I don't { // know how to get away this // circular dependency! // Notice how I should be // defining generics parameters // here but I can't! Value GetStateAt(Position position); void SetStateAt(Position position, State state); } As you'll down here, both IPosition, IValue and IState depend on each other. How am I supposed to get away with this? I can't think of any other design that will circumvent this circular dependency and still describes exactly what I want to do! interface IState<StateSpace, Value> where StateSpace : IStateSpace where Value : IValue { StateSpace StateSpace { get; }; Value Value { get; set; } } interface IPosition { } interface IValue<State> where State : IState { State State { get; } } Basically I have a state space IStateSpace that has states IState inside. Their position in the state space is given by an IPosition. Each state then has one (or more) values IValue. I am simplifying the hierarchy, as it's a bit more complex than described. The idea of having this hierarchy defined with generics is to allow for different implementations of the same concepts (an IStateSpace will be implemented both as a matrix as an graph, etc). Would can I get away with this? How do you generally solve this kind of problems? Which kind of designs are used in these cases? Thanks

    Read the article

  • Need help make these classes use Visitor Pattern and generics

    - by Shervin
    Hi. I need help to generify and implement the visitor pattern. We are using tons of instanceof and it is a pain. I am sure it can be modified, but I am not sure how to do it. Basically we have an interface ProcessData public interface ProcessData { public setDelegate(Object delegate); public Object getDelegate(); //I am sure these delegate methods can use generics somehow } Now we have a class ProcessDataGeneric that implements ProcessData public class ProcessDataGeneric implements ProcessData { private Object delegate; public ProcessDataGeneric(Object delegate) { this.delegate = delegate; } } Now a new interface that retrieves the ProcessData interface ProcessDataWrapper { public ProcessData unwrap(); } Now a common abstract class that implements the wrapper so ProcessData can be retrieved @XmlSeeAlso( { ProcessDataMotorferdsel.class,ProcessDataTilskudd.class }) public abstract class ProcessDataCommon implements ProcessDataWrapper { protected ProcessData unwrapped; public ProcessData unwrap() { return unwrapped; } } Now the implementation public class ProcessDataMotorferdsel extends ProcessDataCommon { public ProcessDataMotorferdsel() { unwrapped = new ProcessDataGeneric(this); } } similarly public class ProcessDataTilskudd extends ProcessDataCommon { public ProcessDataTilskudd() { unwrapped = new ProcessDataGeneric(this); } } Now when I use these classes, I always need to do instanceof ProcessDataCommon pdc = null; if(processData.getDelegate() instanceof ProcessDataMotorferdsel) { pdc = (ProcessDataMotorferdsel) processData.getDelegate(); } else if(processData.getDelegate() instanceof ProcessDataTilskudd) { pdc = (ProcessDataTilskudd) processData.getDelegate(); } I know there is a better way to do this, but I have no idea how I can utilize Generics and the Visitor Pattern. Any help is GREATLY appreciated.

    Read the article

  • Dealing with multiple generics in a method call

    - by thaBadDawg
    I've been dealing a lot lately with abstract classes that use generics. This is all good and fine because I get a lot of utility out of these classes but now it's making for some rather ugly code down the line. For example: abstract class ClassBase<T> { T Property { get; set; } } class MyClass : ClassBase<string> { OtherClass PropertyDetail { get; set; } } This implementation isn't all that crazy, except when I want to reference the abstract class from a helper class and then I have to make a list of generics just to make reference to the implemented class, like this below. class Helper { void HelpMe<C, T>(object Value) where C : ClassBase<T>, new() { DoWork(); } } This is just a tame example, because I have some method calls where the list of where clauses end up being 5 or 6 lines long to handle all of the generic data. What I'd really like to do is class Helper { void HelpMe<C>(object Value) where C : ClassBase, new() { DoWork(); } } but it obviously won't compile. I want to reference ClassBase without having to pass it a whole array of generic classes to get the function to work, but I don't want to reference the higher level classes because there are a dozen of those. Am I the victim of my own cleverness or is there an avenue that I haven't considered yet?

    Read the article

  • C# generics when T could be an array

    - by bufferz
    I am writing a C# wrapper for a 3rd party library that reads both single values and arrays from a hardware device, but always returns an object[] array even for one value. This requires repeated calls to object[0] when I'd like the end user to be able to use generics to receive either an array or single value. I want to use generics so the callee can use the wrapper in the following ways: MyWrapper<float> mw = new MyWrapper<float>( ... ); float value = mw.Value; //should return float; MyWrapper<float[]> mw = new MyWrapper<float[]>( ... ); float[] values = mw.Value; //should return float[]; In MyWrapper I have the Value property currently as the following: public T Value { get { if(_wrappedObject.Values.Length > 1) return (T)_wrappedObject.Value; //T could be float[]. this doesn't compile. else return (T)_wrappedObject.Values[0]; //T could be float. this compiles. } } I get a compile error in the first case: Cannot convert type 'object[]' to 'T' If I change MyWrapper.Value to T[] I receive: Cannot convert type 'object[]' to 'T[]' Any ideas of how to achieve my goal? Thanks!

    Read the article

  • Java generics question with wildcards

    - by Sean
    Just came across a place where I'd like to use generics and I'm not sure how to make it work the way I want. I have a method in my data layer that does a query and returns a list of objects. Here's the signature. public List getList(Class cls, Map query) This is what I'd like the calling code to look like. List<Whatever> list = getList(WhateverImpl.class, query); I'd like to make it so that I don't have to cast this to a List coming out, which leads me to this. public <T> List<T> getList(Class<T> cls, Map query) But now I have the problem that what I get out is always the concrete List<WhateverImpl> passed in whereas I'd like it to be the Whatever interface. I tried to use the super keyword but couldn't figure it out. Any generics gurus out there know how this can be done?

    Read the article

  • Why aren't Java's generics implicitly polymorphic?

    - by froadie
    I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subset of Animal by saying doSomething(List<? extends Animal> animals). I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?

    Read the article

  • Java Generics : What is PECS?

    - by peakit
    Hi, I came across PECS (short for Producer extends and Consumer super) while reading on Generics. Can someone explain me how to use PECS to resolve confusion between extends and super? Thanks in advance !

    Read the article

  • Frustration with generics

    - by sbi
    I have a bunch of functions which are currently overloaded to operate on int and string: bool foo(int); bool foo(string); bool bar(int); bool bar(string); void baz(int p); void baz(string p); I then have a bunch of functions taking 1, 2, 3, or 4 arguments of either int or string, which call the aforementioned functions: void g(int p1) { if(foo(p1)) baz(p1); } void g(string p1) { if(foo(p1)) baz(p1); } void g(int p2, int p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } void g(int p2, string p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } void g(string p2, int p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } void g(string p2, string p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } // etc. (The implementation of the g() family is just a placeholder. actually they are more complicated.) More types than the current int or string might have to be introduced at any time. The same goes for functions with more arguments than 4. The current number of identical functions is barely manageable. Add one more variant in either dimension and the combinatoric explosion will be so huge, it might blow away the application. In C++, I'd templatize g() and be done. I understand that .NET generics are different. <sigh> But I have been fighting them for two hours trying to come up with a solution that doesn't involve too much copy&paste of code. To no avail. Surely, C#/.NET/generics/whatever won't require me to type out identical code for a family of functions taking five arguments of either of three types? So what am I missing here?

    Read the article

  • Generics and anonymous type

    - by nettguy
    I understood,normally generics is for compile time safe and allow us to keep strongly typed collection.Then how do generic allow us to store anonymous types like List<object> TestList = new List<object>(); TestList.Add(new { id = 7, Name = "JonSkeet" }); TestList.Add(new { id = 11, Name = "Marc Gravell" }); TestList.Add(new { id = 31, Name = "Jason" });

    Read the article

  • Why does NUnit ignore datapoints when using generics in a theory

    - by The Chairman
    I'm trying to make use of the TheoryAttribute, introduced in NUnit 2.5. Everything works fine as long as the arguments are of a defined type: [Datapoint] public double[,] Array2X2 = new double[,] { { 1, 0 }, { 0, 1 } }; [Theory] public void TestForArbitraryArray(double[,] array) { // ... } It does not work, when I use generics: [Datapoint] public double[,] Array2X2 = new double[,] { { 1, 0 }, { 0, 1 } }; [Theory] public void TestForArbitraryArray<T>(T[,] array) { // ... } NUnit gives a warning saying No arguments were provided. Why is that?

    Read the article

  • Java generics parameters with base of the generic parameter

    - by Iulian Serbanoiu
    Hello, I am wondering if there's an elegant solution for doing this in Java (besides the obvious one - of declaring a different/explicit function. Here is the code: private static HashMap<String, Integer> nameStringIndexMap = new HashMap<String, Integer>(); private static HashMap<Buffer, Integer> nameBufferIndexMap = new HashMap<Buffer, Integer>(); // and a function private static String newName(Object object, HashMap<Object, Integer> nameIndexMap){ .... } The problem is that I cannot pass nameStringIndexMap or nameBufferIndexMap parameters to the function. I don't have an idea about a more elegant solution beside doing another function which explicitly wants a HashMap<String, Integer> or HashMap<Buffer, Integer> parameter. My question is: Can this be made in a more elegant solution/using generics or something similar? Thank you, Iulian

    Read the article

  • java generics covariance

    - by soocracy42
    I am having trouble understanding the following article: http://www.ibm.com/developerworks/java/library/j-jtp01255.html Under, Generics are not covariant the author states, Because ln is a List, adding a Float to it seems perfectly legal. But if ln were aliased with li, then it would break the type-safety promise implicit in the definition of li -- that it is a list of integers, which is why generic types cannot be covariant. I can't understand the part where it says "if ln were aliased with li". What does the author means by alias?(reference?). The code snippet above the quoted line seems to illustrate WHAT is illegal in java and not WHY. It would be very helpful to me if somebody could explain with an example. Thanks in advance.

    Read the article

  • Java Generics Type Safety warning with recursive Hashmap

    - by GC
    Hi, I'm using a recursive tree of hashmaps, specifically Hashmap map where Object is a reference to another Hashmap and so on. This will be passed around a recursive algorithm: foo(String filename, Hashmap<String, Object> map) { //some stuff here for (Entry<String, Object> entry : map.entrySet()) { //type warning that must be suppressed foo(entry.getKey(), (HashMap<String, Object>)entry.getValue()); } } I know for sure Object is of type Hashmap<String, Object> but am irritated that I have to suppress the warning using @SuppressWarnings("unchecked"). I'll be satisfied with a solution that does either a assert(/*entry.getValue() is of type HashMap<String, Object>*/) or throws an exception when it isn't. I went down the Generics route for compile type safety and if I suppress the warning then it defeats the purpose. Thank you for your comments, ksb

    Read the article

  • Using Generics to typecast object type to generic type

    - by Shantanu Gupta
    I am very new to generics and trying to implement it. How can i use it here. private T returnValueFromGrid(int RowNo, int ColNo) { return Converter<dgvCurrencyMaster.Rows[RowNo].Cells[ColNo].Value,T>; } I am trying to convert below value to generic type and then return it. dgvCurrencyMaster.Rows[RowNo].Cells[ColNo].Value Here i need to know two things. How to do the above problem and how to use this in my code. Please provide some eg.

    Read the article

  • What would be the use of accepting itself as type arguments in generics

    - by Newtopian
    I saw some code on an unrelated question but it got me curious as I never saw such construct with Java Generics. What would be the use of creating a generic class that can take as type argument itself or descendants of itself. Here is example : abstract class A<E extends A> { abstract void foo(E x); } the first thing that came to mind would be a list that takes a list as parameter. Using this code feels strange, how do you declare a variable of type A ? Recursive declaration !? Does this even work ? If so did any of you see that in code ? How was it used ?

    Read the article

  • IBM RAD With Java 1.5 wont compile code with generics

    - by Matt1776
    Hello I have some code that has generic references in it and my IBM RAD IDE will not compile the code, instead treating it as an error. I have checked the version of the JRE its pointing to across all the Enterprise Project's and it is 1.5 which I am told does support generics. Also I checked that all the libraries for WAS were pointing to the correct version and that the Compiler Compliance Level was set correctly (which it was at 5.0 and i changed it to 6.0 with no luck either) Does anyone have any suggestions as to anything else I can try? I have issues like this with RAD all the time and I dont know about anyone else but they took eclipse and made it complicated and dysfunctional.

    Read the article

  • How To Get Type Info Without Using Generics?

    - by DaveDev
    Hi Guys I have an object obj that is passed into a helper method. public static MyTagGenerateTag<T>(this HtmlHelper htmlHelper, T obj /*, ... */) { Type t = typeof(T); foreach (PropertyInfo prop in t.GetProperties()) { object propValue = prop.GetValue(obj, null); string stringValue = propValue.ToString(); dictionary.Add(prop.Name, stringValue); } // implement GenerateTag } I've been told this is not a correct use of generics. Can somebody tell me if I can achieve the same result without specifying a generic type? If so, how? I would probably change the signature so it'd be like: public static MyTag GenerateTag(this HtmlHelper htmlHelper, object obj /*, ... */) { Type t = typeof(obj); // implement GenerateTag } but Type t = typeof(obj); is impossible. Any suggestions? Thanks Dave

    Read the article

  • using extends with Java Generics

    - by Sandro
    Lets say that I have the following code: public class Shelter<A extends Animal, B extends Animal> { List<A> topFloor = new Vector<A>(); List<B> bottomFloor = new Vector<B>(); public A getFirstTopFloorAnimal(){return topFloor.firstElement();} public B getFirstBottomFloorAnimal(){return bottomFloor.firstElement();} //This compiles but when I try to use it, it only returns objects public List<Animal> getAnimals() { Vector a = new Vector(topFloor); a.addAll(bottomFloor); return a; } } Now for somereason the following code compiles. But when I try to use getAnimals() I get a of objects instead of Animal. Any ideas why this is? Does this have to do with the List is NOT a List idea in the Generics tutorial? Thank you.

    Read the article

  • .NET 2.0: Invoking Methods Using Reflection And Generics Causes Exception

    - by David Derringer
    Hi all, I'm new to Stack Overflow, so forgive me. I've just started transititoning over to C# and I am stuck on a problem. I am wanting to pass a generic class in and call a method from that class. So, my code looks as such: public void UpdateRecords<T>(T sender) where T : new() //where T: new() came from Resharper { Type foo = Type.GetType(sender.GetType().ToString()); object[] userParameters = new object[2]; userParameters[0] = x; userParameters[1] = y; sender = new T(); //This was to see if I could solve my exception problem MethodInfo populateRecord = foo.GetMethod("MethodInOtherClass"); populateMethod.Invoke(sender, userParameters); } Exception thrown: "Object reference not set to an instance of an object." Again, I really apologize, as I am nearly brand new to C# and this is the first time I've ever handled reflection and generics. Thank you!

    Read the article

  • C5 Generics Collection IntervalHeap<T> -- getting an IPriorityQueueHandle from a T for Replace or De

    - by Jared Updike
    I'm using the Generics Collection library C5 (server down :-( ) and I have an IntervalHeap(T) and I need to Delete or Replace a T that is not the Max or Min. How do I get an IPriorityQueueHandle from my T? The C5 library source code shows that IPriorityQueueHandle(T) has no methods or properties to implement and the compiler thinks my implementation of IPriorityQueueHandle(T) for my T is acceptable. I try to use a T like this: q.Replace(t, t); and the C5 library throws an InvalidCastException because it cannot convert my T to a (Handle).

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >