Search Results

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

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

  • Map generics in Java

    - by Amir Rachum
    Hi all, I seem to have a bit of misunderstanding with Java Generics and I hope you can help me. I tried to create a map like so: Map<Debater, int> (Debater is an Interface I declared) but java complained about the int, so I did: Map<Debater, Integer> I suppose it's because int is not a class while Integer is, is this correct? Also, Now I get a Debater and I need to add 1 to its value in the map. How do I do that?

    Read the article

  • Generics limitation, or lack of skillz ?

    - by Two Shoes
    I want to define the following class as such: public class CollectionAttribute<E extends Collection<T>> { private String name; private E value; public CollectionAttribute(String name, E value) { this.name = name; this.value = value; } public E getValue() { return value; } public void addValue(T value) { value.add(T); } } This won't compile (cannot resolve symbol T). If I replace the class declaration with the following: public class CollectionAttribute<E extends Collection<?>> Then I can't reference the parametrized type of the collection. Am I missing something or have I reached a limitation with generics in Java ?

    Read the article

  • How do I correctly use generics?

    - by ninjasense
    I basically am making webrequests and recieving a JSON response. Depending on the request, I am parsing JSON request into objects I have created. The parsing is pretty much the same no matter what the object Im parsing into looks like. So I have a bunch of methods doing the same work only with different objects, I was wondering how I could accomplish this with generics? Here is an example public static ArrayList<Contact> parseContacts(String responseData) { ArrayList<Contact> Contacts = new ArrayList<Contact>(); try { JSONArray jsonContacts = new JSONArray(responseData); if (!jsonContacts.isNull(0)) { for (int i = 0; i < jsonContacts.length(); i++) { Contacts.add(new Contact(jsonContacts.getJSONObject(i))); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { } return Contacts; }

    Read the article

  • How do I map nested generics in NHibernate

    - by Gluip
    In NHibernate you can map generics like this <class name="Units.Parameter`1[System.Int32], Units" table="parameter_int" > </class> But how can I map a class like this? Set<T> where T is a Parameter<int> like this Set<Parameter<int>> My mapping hbm.xml looking like this fails <class name="Set`1[[Units.Parameter`1[System.Int32], Units]],Units" table="settable"/> I simplified my mappings a little to get my point accross very clearly. Basically I want NHibernate to map generic class which has has generic type parameter. Want I understand from googling around is that NHibernate is not able to parse the name to the correct type in TypeNameParser.Parse() which result in the following error when adding the mapping to the configuration System.ArgumentException: Exception of type 'System.ArgumentException' was thrown. Parameter name: typeName@31 Anybody found a way around this limitation?

    Read the article

  • C# Generics Multiple Inheritance Problem

    - by Ciemnl
    Can any one help me with this syntax issue with C#? I have no idea how to do it. class SomeClass<T> : SomeOtherClass<T> where T : ISomeInterface , IAnotherInterface { ... } I want SomeClass to inherit from SomeOtherClass and IAnotherInterface and for T to inherit ISomeInterface only It seems the problem is that the where keyword screws everything up so that the compiler thinks both ISomeInterface and IAnotherInterface should both be inherited by T. This problem is very annoying and I think the solution is some kind of parenthesis but I have tried and failed finding one that works. Also, switching around the order of the two items inherited from SomeClass does not work because the class inherited always has to come before any interfaces. I couldn't find any solutions on the MSDN C# generics pages and I can't beleive I'm the first person to have this problem. Thanks, any help is much appreciated!

    Read the article

  • Instantiating a list of parameterized types, making beter use of Generics and Linq

    - by DanO
    I'm hashing a file with one or more hash algorithms. When I tried to parametrize which hash types I want, it got a lot messier than I was hoping. I think I'm missing a chance to make better use of generics or LINQ. I also don't like that I have to use a Type[] as the parameter instead of limiting it to a more specific set of type (HashAlgorithm descendants), I'd like to specify types as the parameter and let this method do the constructing, but maybe this would look better if I had the caller new-up instances of HashAlgorithm to pass in? public List<string> ComputeMultipleHashesOnFile(string filename, Type[] hashClassTypes) { var hashClassInstances = new List<HashAlgorithm>(); var cryptoStreams = new List<CryptoStream>(); FileStream fs = File.OpenRead(filename); Stream cryptoStream = fs; foreach (var hashClassType in hashClassTypes) { object obj = Activator.CreateInstance(hashClassType); var cs = new CryptoStream(cryptoStream, (HashAlgorithm)obj, CryptoStreamMode.Read); hashClassInstances.Add((HashAlgorithm)obj); cryptoStreams.Add(cs); cryptoStream = cs; } CryptoStream cs1 = cryptoStreams.Last(); byte[] scratch = new byte[1 << 16]; int bytesRead; do { bytesRead = cs1.Read(scratch, 0, scratch.Length); } while (bytesRead > 0); foreach (var stream in cryptoStreams) { stream.Close(); } foreach (var hashClassInstance in hashClassInstances) { Console.WriteLine("{0} hash = {1}", hashClassInstance.ToString(), HexStr(hashClassInstance.Hash).ToLower()); } }

    Read the article

  • Generics and collections ... struggling with an implementation

    - by mattruma
    I am trying to figure out a way to leverage generics so I can make the property Value be an actual type that initialized (not sure if this is the correct way of saying it) when my collection class is created. I would like to have the syntax be something like: var list = new ListItemCollection<Guid>(parameters would go here); I have the following class: [Serializable] public class ListItem { public object Value { get; set; } public string Text { get; set; } public object DataContext { get; set; } public Nullable<bool> Checked { get; set; } public ListItem() { this.Checked = false; } } I have the following collection: [Serializable] public class ListItemCollection : List<ListItem> { public ListItem this[object value] { get { foreach (var child in this) { if (child.Value.Equals(value)) return child; } return null; } } public bool Contains(object value) { foreach (var child in this) { if (child.Value.Equals(value)) return true; } return false; } public void Add(object value, string text) { this.Add(value, text, null); } public void Add(object value, string text, object dataContext) { var child = new ListItem(); child.Value = value; child.Text = text; child.DataContext = dataContext; this.Add(child); } public ListItemCollection() { } public ListItemCollection(IEnumerable items, string displayMember, string valueMember, bool showEmptyItem, string emptyItemText, object emptyItemValue) { if (showEmptyItem) { this.Add(emptyItemValue, emptyItemText); } foreach (object item in items) { object text = null; object value = null; text = item.GetType().GetProperty(displayMember).GetValue(item, null); value = item.GetType().GetProperty(valueMember).GetValue(item, null); // Add the item this.Add(value, text.ToString(), item); } } }

    Read the article

  • Java: Generics, Class.isaAssignableFrom, and type casting

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupporteded value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • Using 'or' in Java Generics declaration

    - by Shervin
    I have a method that returns an instance of Map<String, List<Foo>> x(); and another method that returns an instance of Map<String, Collection<Foo>> y(); Now if I want to dynamically add one of this Maps in my field, how can I write the generics for it to work? ie: public class Bar { private Map<String, ? extends Collection<Foo>> myMap; public void initializer() { if(notImportant) myMap = x(); //OK else myMap = y(); // !OK (Need cast to (Map<String, ? extends Collection<Foo>>) } Now is it ok that I cast to the signature even though the y() is declared as being Collection? } } If it is not ok to cast, can I somehow write this (Collection OR List) I mean, List is a Collection, so it should somehow be possible. private Map<String, Collection<Foo> | List<Foo>>> myMap;

    Read the article

  • Structure map and generics (in XML config)

    - by James D
    Hi I'm using the latest StructureMap (2.5.4.264), and I need to define some instances in the xml configuration for StructureMap using generics. However I get the following 103 error: Unhandled Exception: StructureMap.Exceptions.StructureMapConfigurationException: StructureMap configuration failures: Error: 103 Source: Requested PluginType MyTest.ITest`1[[MyTest.Test,MyTest]] configured in Xml cannot be found Could not create a Type for 'MyTest.ITest`1[[MyTest.Test,MyTest]]' System.ApplicationException: Could not create a Type for 'MyTest.ITest`1[[MyTest.Test,MyTest]]' ---> System.TypeLoadException: Could not loa d type 'MyTest.ITest`1' from assembly 'StructureMap, Version=2.5.4.264, Culture=neutral, PublicKeyToken=e60ad81abae3c223'. at System.RuntimeTypeHandle._GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, Boolean loadTypeFromPartialName) at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) at System.RuntimeType.PrivateGetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& s tackMark) at System.Type.GetType(String typeName, Boolean throwOnError) at StructureMap.Graph.TypePath.FindType() --- End of inner exception stack trace --- at StructureMap.Graph.TypePath.FindType() at StructureMap.Configuration.GraphBuilder.ConfigureFamily(TypePath pluginTypePath, Action`1 action) A simply replication of the code is as follows: public interface ITest<T> { } public class Test { } public class Concrete : ITest<Test> { } Which I then wish to define in the XML configuration something as follows: <DefaultInstance PluginType="MyTest.ITest`1[[MyTest.Test,MyTest]],MyTest" PluggedType="MyTest.Concrete,MyTest" Scope="Singleton" /> I've been racking my brain, however I can't see what I'm doing wrong - I've used Type.GetType to verify the type actually is valid which it is. Anyone have any ideas? Thanks !

    Read the article

  • Java: Typecasting to Generics

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupported value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • Weird compile-time behavior when trying to use primitive type in generics

    - by polygenelubricants
    import java.lang.reflect.Array; public class PrimitiveArrayGeneric { static <T> T[] genericArrayNewInstance(Class<T> componentType) { return (T[]) Array.newInstance(componentType, 0); } public static void main(String args[]) { int[] intArray; Integer[] integerArray; intArray = (int[]) Array.newInstance(int.class, 0); // Okay! integerArray = genericArrayNewInstance(Integer.class); // Okay! intArray = genericArrayNewInstance(int.class); // Compile time error: // cannot convert from Integer[] to int[] integerArray = genericArrayNewInstance(int.class); // Run time error: // ClassCastException: [I cannot be cast to [Ljava.lang.Object; } } I'm trying to fully understand how generics works in Java. Things get a bit weird for me in the 3rd assignment in the above snippet: the compiler is complaining that Integer[] cannot be converted to int[]. The statement is 100% true, of course, but I'm wondering WHY the compiler is making this complaint. If you comment that line, and follow the compiler's "suggestion" as in the 4th assignment, the compiler is actually satisfied!!! NOW the code compiles just fine! Which is crazy, of course, since like the run time behavior suggests, int[] cannot be converted to Object[] (which is what T[] is type-erased into at run time). So my question is: why is the compiler "suggesting" that I assign to Integer[] instead for the 3rd assignment? How does the compiler reason to arrive to that (erroneous!) conclusion?

    Read the article

  • Why doesn't the spring @Autowire work with java generics

    - by testing123
    Inspired by spring data awesomeness I wanted to create a abstract RESTController that I could extend for a lot of my controllers. I created the following class: @Controller public abstract class RESTController<E, PK extends Serializable, R extends PagingAndSortingRepository<E, PK>> { @Autowired private R repository; @RequestMapping(method=RequestMethod.GET, params={"id"}) @ResponseBody public E getEntity(@RequestParam PK id) { return repository.findOne(id); } ... } I was hoping that the generics would allow me to @Autowire in the repository but I get the following error: SEVERE: Allocate exception for servlet appServlet org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.data.repository.PagingAndSortingRepository] is defined: expected single matching bean but found 3: [groupRepository, externalCourseRepository, managedCourseRepository] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) I understand what the error is telling me, there is more than one match for the @Autowire. I am confused because I thought by creating the following controller it would work: @Controller @RequestMapping(value="/managedCourse") public class ManagedCourseController extends RESTController<ManagedCourse, Long, ManagedCourseRepository> { ... } This is easy enough to work around by doing having a method like this in the RESTController: protected abstract R getRepository(); and then doing this in your implementing class: @Autowired private ManagedCourseRepository repository; @Override protected ManagedCourseRepository getRepository() { return repository; } I was just wondering if someone had any thoughts of how I could get this to work.

    Read the article

  • Generics in return types of static methods and inheritance

    - by Axel
    Generics in return types of static methods do not seem to get along well with inheritance. Please take a look at the following code: class ClassInfo<C> { public ClassInfo(Class<C> clazz) { this(clazz,null); } public ClassInfo(Class<C> clazz, ClassInfo<? super C> superClassInfo) { } } class A { public static ClassInfo<A> getClassInfo() { return new ClassInfo<A>(A.class); } } class B extends A { // Error: The return type is incompatible with A.getClassInfo() public static ClassInfo<B> getClassInfo() { return new ClassInfo<B>(B.class, A.getClassInfo()); } } I tried to circumvent this by changing the return type for A.getClassInfo(), and now the error pops up at another location: class ClassInfo<C> { public ClassInfo(Class<C> clazz) { this(clazz,null); } public ClassInfo(Class<C> clazz, ClassInfo<? super C> superClassInfo) { } } class A { public static ClassInfo<? extends A> getClassInfo() { return new ClassInfo<A>(A.class); } } class B extends A { public static ClassInfo<? extends B> getClassInfo() { // Error: The constructor ClassInfo<B>(Class<B>, ClassInfo<capture#1-of ? extends A>) is undefined return new ClassInfo<B>(B.class, A.getClassInfo()); } } What is the reason for this strict checking on static methods? And how can I get along? Changing the method name seems awkward.

    Read the article

  • Is it possible to tie nested generics?

    - by Michael Deardeuff
    Is it possible to tie nested generics/captures together? I often have the problem of having a Map lookup of class to genericized item of said class. In concrete terms I want something like this (no, T is not declared anywhere). private Map<Class<T>, ServiceLoader<T>> loaders = Maps.newHashMap(); In short, I want loaders.put/get to have semantics something like these: <T> ServiceLoader<T> get(Class<T> klass) {...} <T> void put(Class<T> klass, ServiceLoader<T> loader) {...} Is the following the best I can do? Do I have to live with the inevitable @SuppressWarnings("unchecked") somewhere down the line? private Map<Class<?>, ServiceLoader<?>> loaders = Maps.newHashMap();

    Read the article

  • Java Generics error when implementing Hibernate message interpolator

    - by Jayaprakash
    Framework: Spring, Hibernate. O/S: Windows I am trying to implement hibernate's Custom message interpolator following the direction of this Link. When implementing the below class, it gives an error "Cannot make a static reference to the non-static type Locale". public class ClientLocaleThreadLocal<Locale> { private static ThreadLocal tLocal = new ThreadLocal(); public static void set(Locale locale) { tLocal.set(locale); } public static Locale get() { return tLocal.get(); } public static void remove() { tLocal.remove(); } } As I do not know generics enough, not sure how is being used by TimeFilter class below and the purpose of definition in the above class. public class TimerFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { try { ClientLocaleThreadLocal.set(req.getLocale()); filterChain.doFilter(req, res); }finally { ClientLocaleThreadLocal.remove(); } } public void init(FilterConfig arg0) throws ServletException { } } Will doing the following be okay? Change static method/field in ClientLocaleThreadLocal to non-static method/fields In TimeFilter, set locale by instantiating new object as below. new ClientLocaleThreadLocal().set(req.getLocale()) Thanks for your help in advance

    Read the article

  • Utilizing Generics to make a Class structure more mutable…

    - by Keith Barrows
    While the ASP.NET GridView control supports automatic paging I found it faster to use custom paging in several situations.  I found myself rewriting the same code over and over just to add the basic sorting capabilities to an ASP.NET GridView object.  So today I took just a little bit of time to encapsulate it all into a Class I can use and reuse on any page with a GridView.  In fact, it will probably take longer to write this blog entry than it took to encapsulate the functionality...(read more)

    Read the article

  • Do functional generics exist and what is the correct name for them if they do?

    - by voroninp
    Consider the following generic class: public class EntityChangeInfo<EntityType,TEntityKey> { ChangeTypeEnum ChangeType {get;} TEntityKeyType EntityKey {get;} } Here EntityType unambiguously defines TEntityKeyType. So it would be nice to have some kind of types' map: public class EntityChangeInfo<EntityType,TEntityKey> with map < [ EntityType : Person -> TEntityKeyType : int] [ EntityType : Car -> TEntityKeyType : CarIdType ]> { ChangeTypeEnum ChangeType {get;} TEntityKeyType EntityKey {get;} } Another one example is: public class Foo<TIn> with map < [TIn : Person -> TOut1 : string, TOut2 : int, ..., TOutN : double ] [TIn : Car -> TOut1 : int, TOut2 :int, ..., TOutN : Price ] > { TOut1 Prop1 {get;set;} TOut2 Prop2 {get;set;} ... TOutN PropN {get;set;} } The reasonable question: how can this be interpreted by the compiler? Well, for me it is just the shortcut for two structurally similar classes: public sealed class Foo<Person> { string Prop1 {get;set;} int Prop2 {get;set;} ... double PropN {get;set;} } public sealed class Foo<Car> { int Prop1 {get;set;} int Prop2 {get;set;} ... Price PropN {get;set;} } But besides this we could imaging some update of the Foo<>: public class Foo<TIn> with map < [TIn : Person -> TOut1 : string, TOut2 : int, ..., TOutN : double ] [TIn : Car -> TOut1 : int, TOut2 :int, ..., TOutN : Price ] > { TOut1 Prop1 {get;set;} TOut2 Prop2 {get;set;} ... TOutN PropN {get;set;} public override string ToString() { return string.Format("prop1={0}, prop2={1},...propN={N-1}, Prop1, Prop2,...,PropN); } } This all can seem quite superficial but the idea came when I was designing the messages for our system. The very first class. Many messages with the same structure should be discriminated by the EntityType. So the question is whether such construct exists in any programming language?

    Read the article

  • Do functional generics exist or what is the correct name for them if they do?

    - by voroninp
    Consider the following generic class public class EntityChangeInfo<EntityType,TEntityKey> { ChangeTypeEnum ChangeType {get;} TEntityKeyType EntityKey {get;} } Here EntityType unambiguously defines TEntityKeyType. So it would be nice to have some kind of types' map public class EntityChangeInfo<EntityType,TEntityKey> with map < [ EntityType : Person -> TEntityKeyType : int] [ EntityType : Car -> TEntityKeyType : CarIdType ]> { ChangeTypeEnum ChangeType {get;} TEntityKeyType EntityKey {get;} } Another one example is: public class Foo<TIn> with map < [TIn : Person -> TOut1 : string, TOut2 : int, ..., TOutN : double ] [TIn : Car -> TOut1 : int, TOut2 :int, ..., TOutN : Price ] > { TOut1 Prop1 {get;set;} TOut2 Prop2 {get;set;} ... TOutN PropN {get;set;} } The reasonable question how this can be interpreted by the compiler? Well, for me it is just the sortcut for two structurally similar classes: public sealed class Foo<Person> { string Prop1 {get;set;} int Prop2 {get;set;} ... double PropN {get;set;} } public sealed class Foo<Car> { int Prop1 {get;set;} int Prop2 {get;set;} ... Price PropN {get;set;} } But besides this we could imaging some update of the Foo<: public class Foo<TIn> with map < [TIn : Person -> TOut1 : string, TOut2 : int, ..., TOutN : double ] [TIn : Car -> TOut1 : int, TOut2 :int, ..., TOutN : Price ] > { TOut1 Prop1 {get;set;} TOut2 Prop2 {get;set;} ... TOutN PropN {get;set;} public override string ToString() { return string.Format("prop1={0}, prop2={1},...propN={N-1}, Prop1, Prop2,...,PropN); } } This all can seem quite superficial but the idea came when I was designing the messages for our system. The very first class. Many messages with the same structrue should be discriminated by the EntityType. So the question is whether such construct exist in any programming language?

    Read the article

  • C#/.NET Little Wonders: Constraining Generics with Where Clause

    - by James Michael Hare
    Back when I was primarily a C++ developer, I loved C++ templates.  The power of writing very reusable generic classes brought the art of programming to a brand new level.  Unfortunately, when .NET 1.0 came about, they didn’t have a template equivalent.  With .NET 2.0 however, we finally got generics, which once again let us spread our wings and program more generically in the world of .NET However, C# generics behave in some ways very differently from their C++ template cousins.  There is a handy clause, however, that helps you navigate these waters to make your generics more powerful. The Problem – C# Assumes Lowest Common Denominator In C++, you can create a template and do nearly anything syntactically possible on the template parameter, and C++ will not check if the method/fields/operations invoked are valid until you declare a realization of the type.  Let me illustrate with a C++ example: 1: // compiles fine, C++ makes no assumptions as to T 2: template <typename T> 3: class ReverseComparer 4: { 5: public: 6: int Compare(const T& lhs, const T& rhs) 7: { 8: return rhs.CompareTo(lhs); 9: } 10: }; Notice that we are invoking a method CompareTo() off of template type T.  Because we don’t know at this point what type T is, C++ makes no assumptions and there are no errors. C++ tends to take the path of not checking the template type usage until the method is actually invoked with a specific type, which differs from the behavior of C#: 1: // this will NOT compile! C# assumes lowest common denominator. 2: public class ReverseComparer<T> 3: { 4: public int Compare(T lhs, T rhs) 5: { 6: return lhs.CompareTo(rhs); 7: } 8: } So why does C# give us a compiler error even when we don’t yet know what type T is?  This is because C# took a different path in how they made generics.  Unless you specify otherwise, for the purposes of the code inside the generic method, T is basically treated like an object (notice I didn’t say T is an object). That means that any operations, fields, methods, properties, etc that you attempt to use of type T must be available at the lowest common denominator type: object.  Now, while object has the broadest applicability, it also has the fewest specific.  So how do we allow our generic type placeholder to do things more than just what object can do? Solution: Constraint the Type With Where Clause So how do we get around this in C#?  The answer is to constrain the generic type placeholder with the where clause.  Basically, the where clause allows you to specify additional constraints on what the actual type used to fill the generic type placeholder must support. You might think that narrowing the scope of a generic means a weaker generic.  In reality, though it limits the number of types that can be used with the generic, it also gives the generic more power to deal with those types.  In effect these constraints says that if the type meets the given constraint, you can perform the activities that pertain to that constraint with the generic placeholders. Constraining Generic Type to Interface or Superclass One of the handiest where clause constraints is the ability to specify the type generic type must implement a certain interface or be inherited from a certain base class. For example, you can’t call CompareTo() in our first C# generic without constraints, but if we constrain T to IComparable<T>, we can: 1: public class ReverseComparer<T> 2: where T : IComparable<T> 3: { 4: public int Compare(T lhs, T rhs) 5: { 6: return lhs.CompareTo(rhs); 7: } 8: } Now that we’ve constrained T to an implementation of IComparable<T>, this means that our variables of generic type T may now call any members specified in IComparable<T> as well.  This means that the call to CompareTo() is now legal. If you constrain your type, also, you will get compiler warnings if you attempt to use a type that doesn’t meet the constraint.  This is much better than the syntax error you would get within C++ template code itself when you used a type not supported by a C++ template. Constraining Generic Type to Only Reference Types Sometimes, you want to assign an instance of a generic type to null, but you can’t do this without constraints, because you have no guarantee that the type used to realize the generic is not a value type, where null is meaningless. Well, we can fix this by specifying the class constraint in the where clause.  By declaring that a generic type must be a class, we are saying that it is a reference type, and this allows us to assign null to instances of that type: 1: public static class ObjectExtensions 2: { 3: public static TOut Maybe<TIn, TOut>(this TIn value, Func<TIn, TOut> accessor) 4: where TOut : class 5: where TIn : class 6: { 7: return (value != null) ? accessor(value) : null; 8: } 9: } In the example above, we want to be able to access a property off of a reference, and if that reference is null, pass the null on down the line.  To do this, both the input type and the output type must be reference types (yes, nullable value types could also be considered applicable at a logical level, but there’s not a direct constraint for those). Constraining Generic Type to only Value Types Similarly to constraining a generic type to be a reference type, you can also constrain a generic type to be a value type.  To do this you use the struct constraint which specifies that the generic type must be a value type (primitive, struct, enum, etc). Consider the following method, that will convert anything that is IConvertible (int, double, string, etc) to the value type you specify, or null if the instance is null. 1: public static T? ConvertToNullable<T>(IConvertible value) 2: where T : struct 3: { 4: T? result = null; 5:  6: if (value != null) 7: { 8: result = (T)Convert.ChangeType(value, typeof(T)); 9: } 10:  11: return result; 12: } Because T was constrained to be a value type, we can use T? (System.Nullable<T>) where we could not do this if T was a reference type. Constraining Generic Type to Require Default Constructor You can also constrain a type to require existence of a default constructor.  Because by default C# doesn’t know what constructors a generic type placeholder does or does not have available, it can’t typically allow you to call one.  That said, if you give it the new() constraint, it will mean that the type used to realize the generic type must have a default (no argument) constructor. Let’s assume you have a generic adapter class that, given some mappings, will adapt an item from type TFrom to type TTo.  Because it must create a new instance of type TTo in the process, we need to specify that TTo has a default constructor: 1: // Given a set of Action<TFrom,TTo> mappings will map TFrom to TTo 2: public class Adapter<TFrom, TTo> : IEnumerable<Action<TFrom, TTo>> 3: where TTo : class, new() 4: { 5: // The list of translations from TFrom to TTo 6: public List<Action<TFrom, TTo>> Translations { get; private set; } 7:  8: // Construct with empty translation and reverse translation sets. 9: public Adapter() 10: { 11: // did this instead of auto-properties to allow simple use of initializers 12: Translations = new List<Action<TFrom, TTo>>(); 13: } 14:  15: // Add a translator to the collection, useful for initializer list 16: public void Add(Action<TFrom, TTo> translation) 17: { 18: Translations.Add(translation); 19: } 20:  21: // Add a translator that first checks a predicate to determine if the translation 22: // should be performed, then translates if the predicate returns true 23: public void Add(Predicate<TFrom> conditional, Action<TFrom, TTo> translation) 24: { 25: Translations.Add((from, to) => 26: { 27: if (conditional(from)) 28: { 29: translation(from, to); 30: } 31: }); 32: } 33:  34: // Translates an object forward from TFrom object to TTo object. 35: public TTo Adapt(TFrom sourceObject) 36: { 37: var resultObject = new TTo(); 38:  39: // Process each translation 40: Translations.ForEach(t => t(sourceObject, resultObject)); 41:  42: return resultObject; 43: } 44:  45: // Returns an enumerator that iterates through the collection. 46: public IEnumerator<Action<TFrom, TTo>> GetEnumerator() 47: { 48: return Translations.GetEnumerator(); 49: } 50:  51: // Returns an enumerator that iterates through a collection. 52: IEnumerator IEnumerable.GetEnumerator() 53: { 54: return GetEnumerator(); 55: } 56: } Notice, however, you can’t specify any other constructor, you can only specify that the type has a default (no argument) constructor. Summary The where clause is an excellent tool that gives your .NET generics even more power to perform tasks higher than just the base "object level" behavior.  There are a few things you cannot specify with constraints (currently) though: Cannot specify the generic type must be an enum. Cannot specify the generic type must have a certain property or method without specifying a base class or interface – that is, you can’t say that the generic must have a Start() method. Cannot specify that the generic type allows arithmetic operations. Cannot specify that the generic type requires a specific non-default constructor. In addition, you cannot overload a template definition with different, opposing constraints.  For example you can’t define a Adapter<T> where T : struct and Adapter<T> where T : class.  Hopefully, in the future we will get some of these things to make the where clause even more useful, but until then what we have is extremely valuable in making our generics more user friendly and more powerful!   Technorati Tags: C#,.NET,Little Wonders,BlackRabbitCoder,where,generics

    Read the article

  • Java generics: What is the compiler's issue here?

    - by Epaga
    I have the following methods: public <T> T fromJson( Reader jsonData, Class<T> clazz ) { return fromJson( jsonData, (Type)clazz ); } public <T> T fromJson( Reader jsonData, Type clazz ) { ... } The compiler is saying about the first method: type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds T,java.lang.Object return fromJson( jsonData, (Type)clazz ); ^ What is the problem?

    Read the article

  • .NET converting simple arrays to List Generics

    - by Manish Sinha
    This question might seem trivial and also stupid at the first glance, but it is much more than this. I have an array of any type T (T[]) and I want to convert it into a List generic (List<T>). Is there any other way apart from creating a Generic list, traversing the whole array and adding the element in the List? Present Situation: string[] strList = {'foo','bar','meh'}; List<string> listOfStr = new List<string>(); foreach(string s in strList) { listOfStr.Add(s); } My ideal situation: string[] strList = {'foo','bar','meh'}; List<string> listOfStr = strList.ToList<string>(); Or: string[] strList = {'foo','bar','meh'}; List<string> listOfStr = new List<string>(strList); I am suggesting the last 2 method names as I think compiler or CLR can perform some optimizations on the whole operations if It want inbuilt. P.S.: I am not talking about the Array or ArrayList Type

    Read the article

  • C#: Semantics for generics?

    - by Rosarch
    I have a list: private readonly IList<IList<GameObjectController>> removeTargets; PickUp inherits from GameObjectController. But when I try this: public IList<PickUp> Inventory // ... gameObjectManager.MoveFromListToWorld(this, user.Model.Inventory); I get a compiler error: cannot convert from 'System.Collections.Generic.IList' to 'System.Collections.Generic.IList' Why does this occur? Shouldn't this be fine, since PickUp is a subclass of GameObjectController? Do I need something like Java's Map<E extends GameObjectController>? Earlier, I was having a similar problem, where I was trying to implicitly cast inventory from an IList to an ICollection. Is this the same problem?

    Read the article

  • Java Generics: Dealing with an intermediate unknown type

    - by Matt
    I am trying to figure out a way to deal with a particular problem in a type safe manner, or to put it more specifically without any explicit casts. I have a class that takes in a generic request and returns a generic response like such: public class RetrievalProcessor<Req extends Request, Resp> implements RequestProcessor<Req, Resp>{ private Dao<Req> dao; private RawResponseTransformer<Resp> transformer; @Override public Resp process(Req request) { return transformer.transformResponse(dao.retrieveRawResponse(request)); } } My problem is the following. My Dao object can be many different things REST, JDBC, some other proprietary object. I can't be certain of the type of object that the Dao will return. I do know the type of object my caller would like and that is the Resp type on the generic, and the job of the RawResponseTransformer is to transform that Dao response into something that the caller can consume. The problem I have is I can't figure out a way that feels clean to do that. I have considered putting the intermediate type as part of the definition of the class, but it doesn't seem like the caller should know, or really care, what the intermediate form is. Hoping someone might have a good clean idea for handling this.

    Read the article

  • Java Generics name clash, method not correctly overriden

    - by Shervin
    Hi. I have seen different questions regarding this, but I still find this topic to be very confusing. All I want to do, is have an abstract class that implements an interface, and have a class extending this abstract class so that the hard class needs to implement getKommune() and setKommune(Kommune kommune), but not the other method, because that is in the abstract class. I have the following interface. public interface KommuneFilter { <E extends AbstractKommune<?>> void addKommuneFromCurrentUser(E e); Kommune getKommune(); void setKommune(Kommune kommune); } And this Abstract class public abstract class AbstractKommune<E extends AbstractKommune<?>> implements KommuneFilter { @PrePersist void addKommuneFromCurrentUser(E e) { } } And I want to use it like this public class Person extends AbstractKommune<Person> { private Kommune kommune; public void setKommune(Kommune kommune) {this.kommune=kommune;} public Kommune getKommune() {return kommune;} } However, I get Name clash: The method of has the same erasure of type but does not override it Why isn't it correctly overriden?

    Read the article

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