Search Results

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

Page 11/41 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Delphi: RTTI and TObjectList<TObject>

    - by conciliator
    Based on one answer to an earlier post, I'm investigating the possibility of the following design TChildClass = class(TObject) private FField1: string; FField2: string; end; TMyClass = class(TObject) private FField1: TChildClass; FField2: TObjectList<TChildClass>; end; Now, in the real world, TMyClass will have 10 different lists like this, so I would like to be able to address these lists using RTTI. However, I'm not interested in the other fields of this class, so I need to check if a certain field is some sort of TObjectList. This is what I've got so far: procedure InitializeClass(RContext: TRttiContext; AObject: TObject); var ROwnerType: TRttiType; RObjListType: TRttiType; RField: TRttiField; SchInf: TSchemaInfoDetail; begin ROwnerType := RContext.GetType(AObject.ClassInfo); RObjListType := RContext.GetType(TObjectList<TObject>); for RField in ROwnerType.GetFields do begin // How do I check if the type of TMyClass.FField2 (which is TObjectList<TChildClass>) is some sort of TObjectList? end; Clearly, RField.FieldType <> RObjListType.FieldType. However, they do have some relation, don't they? It seems horrible (and wrong!) to make a very elaborate check for common functionality in order to make it highly probable that RField.FieldType is in fact a TObjectList. To be honest, I am quite uncomfortable with generics, so the question might be very naïve. However, I'm more than happy to learn. Is the above solution possible to implement? TIA!

    Read the article

  • Annotation to make available generic type

    - by mdma
    Given an generic interface like interface DomainObjectDAO<T> { T newInstance(); add(T t); remove(T t); T findById(int id); // etc... } I'd like to create a subinterface that specifies the type parameter: interface CustomerDAO extends DomainObjectDAO<Customer> { // customer-specific queries - incidental. } The implementation needs to know the actual template parameter type, but of course type erasure means isn't available at runtime. Is there some annotation that I could include to declare the interface type? Something like @GenericParameter(Customer.class) interface CustomerDAO extends DomainObjectDAO<Customer> { } The implementation could then fetch this annotation from the interface and use it as a substitute for runtime generic type access. Some background: This interface is implemented using JDK dynamic proxies as outlined here. The non-generic version of this interface has been working well, but it would be nicer to use generics and not have to create a subinterface for each domain object type. The actual type is needed at runtime to implement the newInstance method, amongst others.

    Read the article

  • Problem with MessageContract, Generic return types and clientside naming

    - by Soeteman
    I'm building a web service which uses MessageContracts, because I want to add custom fields to my SOAP header. In a previous topic, I learned that a composite response has to be wrapped. For this purpose, I devised a generic ResponseWrapper class. [MessageContract(WrapperNamespace = "http://mynamespace.com", WrapperName="WrapperOf{0}")] public class ResponseWrapper<T> { [MessageBodyMember(Namespace = "http://mynamespace.com")] public T Response { get; set; } } I made a ServiceResult base class, defined as follows: [MessageContract(WrapperNamespace = "http://mynamespace.com")] public class ServiceResult { [MessageBodyMember] public bool Status { get; set; } [MessageBodyMember] public string Message { get; set; } [MessageBodyMember] public string Description { get; set; } } To be able to include the request context in the response, I use a derived class of ServiceResult, which uses generics: [MessageContract(WrapperNamespace = "http://mynamespace.com", WrapperName = "ServiceResultOf{0}")] public class ServiceResult<TRequest> : ServiceResult { [MessageBodyMember] public TRequest Request { get; set; } } This is used in the following way [OperationContract()] ResponseWrapper<ServiceResult<HCCertificateRequest>> OrderHealthCertificate(RequestContext<HCCertificateRequest> context); I expected my client code to be generated as ServiceResultOfHCCertificateRequest OrderHealthCertificate(RequestContextOfHCCertificateRequest context); Instead, I get the following: ServiceResultOfHCCertificateRequestzSOTD_SSj OrderHealthCertificate(CompType1 c1, CompType2 c2, HCCertificateRequest context); CompType1 and CompType2 are properties of the RequestContext class. The problem is that a hash is added to the end of ServiceResultOfHCCertificateRequestzSOTD_SSj. How do I need define my generic return types in order for the client type to be generated as expected (without the hash)?

    Read the article

  • Accessing Static Methods on a Generic class in c#

    - by mrlane
    Hello, I have the following situation in code, which I suspect may be a bit dodgey: I have a class: abstract class DataAccessBase<T> : IDataAccess where T : AnotherAbstractClass This class DataAccessBase also has a static factory method which creates instances of derived classes of itself using an enum value in a which statement to decide which derived type to create: static IDataAccess CreateInstance(TypeToCreateEnum) Now, the types derived from DataAccessBase<T> are themselves NOT generic, they specify a type for T: class PoLcZoneData : DataAccessBase<PoLcZone> // PoLcZone is derived from AnotherAbstractClass So far I am not sure if this is pushing the limits of good use of generics, but what I am really concerned about is how to access the static CreateInstance() method in the first place: The way I am doing this at the moment is to simply pass any type T where T : AnotherAbstractClass. In particular I am passing AnotherAbstractClass itself. This allows compilation just fine, but it does seem to me that passing any type to a generic class just to get at the statics is a bit dodgey. I have actually simplified the situation somewhat as DataAccessBase<T> is the lower level in the inheritance chain, but the static factory methods exists in a middle tier with classes such as PoLcZoneData being the most derived on the only level that is not generic. What are peoples thoughts on this arrangement?

    Read the article

  • Java Generic Casting Type Mismatch

    - by Kay
    public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; public void main(String[] args){ int i; T[] arr = {1,3,4,5,2}; //ERROR HERE ******* foo } public T[] Heapsort(T[]anArray, int n){ // build initial heap T[]sortedArray = anArray; for (int i = n-1; i< 0; i--){ //assert: the tree rooted at index is a semiheap heapRebuild(anArray, i, n); //assert: the tree rooted at index is a heap } //sort the heap array int last = n-1; //invariant: Array[0..last] is a heap, //Array[last+1..n-1] is sorted for (int j=1; j<n-1;j++) { sortedArray[0]=sortedArray[last]; last--; heapRebuild(anArray, 0, last); } return sortedArray; } protected void heapRebuild(T[ ] items, int root, int size){ foo } } The error is on the line with "T[arr] = {1,3,4,5,2}" Eclispe complains that there is a: "Type mismatch: cannot convert from int to T" I've tried to casting nearly everywhere but to no avail.A simple way out would be to not use generics but instead just ints but that's sadly not an option. I've got to find a way to resolve the array of ints "{1,3,4,5,2}" into an array of T so that the rest of my code will work smoothly.

    Read the article

  • “Could not find type” error loading a form in the Designer

    - by Vaccano
    This is the exact same question as this one: “Could not find type” error loading a form in the Designer Before anyone goes closing my question please read that one. You will realize that it did not get a real answer. I hope to get a full answer (rather than a workaround) from this question. When I create a class that descends from Control and uses generics, that class fails to load in the designer. Here is and example: class OwnerDrawnListBox<T> : System.Windows.Forms.Control { private readonly List<T> _items; // Other list box private stuff here public OwnerDrawnListBox() { _items = new List<T>(); } // More List box code } I then use this in my designer: private OwnerDrawnListBox<Bag> lstAvailable; private void InitializeComponent() { // Used to be System.Windows.Forms.ListBox(); this.lstAvailable = new ARUP.ScanTrack.Mobile.OwnerDrawnListBox<Bag>(); // Other items } If the generic class is subclassed (to a non-generic) then the referenced question says that it works fine (ie if I made Class BagOwnerDrawListBox: OwnerDrawnListBox<Bag>). What I want to know is there a way to "fix" this so that the generic item is accepted by the designer? Side Note: I am using the Compact Framework.

    Read the article

  • Generic object to object mapping with parametrized constructor

    - by Rody van Sambeek
    I have a data access layer which returns an IDataRecord. I have a WCF service that serves DataContracts (dto's). These DataContracts are initiated by a parametrized constructor containing the IDataRecord as follows: [DataContract] public class DataContractItem { [DataMember] public int ID; [DataMember] public string Title; public DataContractItem(IDataRecord record) { this.ID = Convert.ToInt32(record["ID"]); this.Title = record["title"].ToString(); } } Unfortanately I can't change the DAL, so I'm obliged to work with the IDataRecord as input. But in generat this works very well. The mappings are pretty simple most of the time, sometimes they are a bit more complex, but no rocket science. However, now I'd like to be able to use generics to instantiate the different DataContracts to simplify the WCF service methods. I want to be able to do something like: public T DoSomething<T>(IDataRecord record) { ... return new T(record); } So I'd tried to following solutions: Use a generic typed interface with a constructor. doesn't work: ofcourse we can't define a constructor in an interface Use a static method to instantiate the DataContract and create a typed interface containing this static method. doesn't work: ofcourse we can't define a static method in an interface Use a generic typed interface containing the new() constraint doesn't work: new() constraint cannot contain a parameter (the IDataRecord) Using a factory object to perform the mapping based on the DataContract Type. does work, but: not very clean, because I now have a switch statement with all mappings in one file. I can't find a real clean solution for this. Can somebody shed a light on this for me? The project is too small for any complex mapping techniques and too large for a "switch-based" factory implementation.

    Read the article

  • Strongly Typed Controls in .NET

    - by Tigraine
    I am working on a Windows Forms app for quite some time now, and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code. What I mean becomes apparent if you watch the ComboBox control that accepts some vague "object" as it's item. Then you go off and may display some DisplayMember and a ValueMember and so on. If I want to retrieve that value later I need to typecast my object back to what it was. Like with strings getting the value takes string value = (string)combobox1.SelectedItem; Since there are generics in the Framework for quite some time now, I still wonder why in the Hell not one control from the standard toolbox is generic. I also find myself using the .Tag property on ListViewItems all the time to keep the displayed domain object. But everytime I need to access that object I then need another typecast. Why cant I just create a ComboBox or ListView with items of type ListViewItem Am I missing something here or is this just another example of not perfectly well thought through controls?

    Read the article

  • How to find the first declaring method for a reference method

    - by Oliver Gierke
    Suppose you have a generic interface and an implementation: public interface MyInterface<T> { void foo(T param); } public class MyImplementation<T> implements MyInterface<T> { void foo(T param) { } } These two types are frework types. In the next step I want allow users to extend that interface as well as redeclare foo(T param) to maybe equip it with further annotations. public interface MyExtendedInterface extends MyInterface<Bar> { @Override void foo(Bar param); // Further declared methods } I create an AOP proxy for the extended interface and intercept especially the calls to furtherly declared methods. As foo(…) is no redeclared in MyExtendedInterface I cannot execute it by simply invoking MethodInvocation.proceed() as the instance of MyImplementation only implements MyInterface.foo(…) and not MyExtendedInterface.foo(…). So is there a way to get access to the method that declared a method initially? Regarding this example is there a way to find out that foo(Bar param) was declared in MyInterface originally and get access to the accoriding Method instance? I already tried to scan base class methods to match by name and parameter types but that doesn't work out as generics pop in and MyImplementation.getMethod("foo", Bar.class) obviously throws a NoSuchMethodException. I already know that MyExtendedInterface types MyInterface to Bar. So If I could create some kind of "typed view" on MyImplementation my math algorithm could work out actually.

    Read the article

  • How to get a Class literal from a generically specific Class

    - by h2g2java
    There are methods like these which require Class literals as argument. Collection<EmpInfo> emps = SomeSqlUtil.select( EmpInfo.class, "select * from emps"); or GWT.create(Razmataz.class); The problem presents itself when I need to supply generic specific classes like EmpInfo<String> Razmataz<Integer> The following would be wrong syntax Collection<EmpInfo<String>> emps = SomeSqlUtil.select( EmpInfo<String>.class, "select * from emps"); or GWT.create(Razmataz<Integer>.class); Because you cannot do syntax like Razmataz<Integer>.class So, how would I be able to squeeze a class literal out of EmpInfo<String> Razmataz<Integer> so that I could feed them as arguments to methods requiring Class literals? Further info Okay, I confess that I am asking this primarily for GWT. I have a pair of GWT RPC interface Razmataz. (FYI, GWT RPC interface has to be defined in server-client pairs). I plan to use the same interface pair for communicating whether it be String, Integer, Boolean, etc. GWT.create(Razmataz) for Razmataz<T> complains that, since I did not specify T, GWT compiler treated it as Object. Then GWT compiler would not accept Object class. It needs to be more specific than being an Object. So, it seems there is no way for me to tell GWT.create what T is because a Class literal is a runtime concept while generics is a compile time concept, Right?

    Read the article

  • Are there pitfalls to using static class/event as an application message bus

    - by Doug Clutter
    I have a static generic class that helps me move events around with very little overhead: public static class MessageBus<T> where T : EventArgs { public static event EventHandler<T> MessageReceived; public static void SendMessage(object sender, T message) { if (MessageReceived != null) MessageReceived(sender, message); } } To create a system-wide message bus, I simply need to define an EventArgs class to pass around any arbitrary bits of information: class MyEventArgs : EventArgs { public string Message { get; set; } } Anywhere I'm interested in this event, I just wire up a handler: MessageBus<MyEventArgs>.MessageReceived += (s,e) => DoSomething(); Likewise, triggering the event is just as easy: MessageBus<MyEventArgs>.SendMessage(this, new MyEventArgs() {Message="hi mom"}); Using MessageBus and a custom EventArgs class lets me have an application wide message sink for a specific type of message. This comes in handy when you have several forms that, for example, display customer information and maybe a couple forms that update that information. None of the forms know about each other and none of them need to be wired to a static "super class". I have a couple questions: fxCop complains about using static methods with generics, but this is exactly what I'm after here. I want there to be exactly one MessageBus for each type of message handled. Using a static with a generic saves me from writing all the code that would maintain the list of MessageBus objects. Are the listening objects being kept "alive" via the MessageReceived event? For instance, perhaps I have this code in a Form.Load event: MessageBus<CustomerChangedEventArgs>.MessageReceived += (s,e) => DoReload(); When the Form is Closed, is the Form being retained in memory because MessageReceived has a reference to its DoReload method? Should I be removing the reference when the form closes: MessageBus<CustomerChangedEventArgs>.MessageReceived -= (s,e) => DoReload();

    Read the article

  • using STI and ActiveRecordBase<> with full FindAll

    - by oillio
    Is it possible to use generic support with single table inheritance, and still be able to FindAll of the base class? As a bonus question, will I be able to use ActiveRecordLinqBase< as well? I do love those queries. More detail: Say I have the following classes defined: public interface ICompany { int ID { get; set; } string Name { get; set; } } [ActiveRecord("companies", DiscriminatorColumn="type", DiscriminatorType="String", DiscriminatorValue="NA")] public abstract class Company<T> : ActiveRecordBase<T>, ICompany { [PrimaryKey] private int Id { get; set; } [Property] public String Name { get; set; } } [ActiveRecord(DiscriminatorValue="firm")] public class Firm : Company<Firm> { [Property] public string Description { get; set; } } [ActiveRecord(DiscriminatorValue="client")] public class Client : Company<Client> { [Property] public int ChargeRate { get; set; } } This works fine for most cases. I can do things like: var x = Client.FindAll(); But sometimes I want all of the companies. If I was not using generics I could do: var x = (Company[]) FindAll(Company); Client a = (Client)x[0]; Firm b = (Firm)x[1]; Is there a way to write a FindAll that returns an array of ICompany's that can then be typecast into their respective types? Something like: var x = (ICompany[]) FindAll(Company<ICompany>); Client a = (Client)x[0]; Or maybe I am going about implementing the generic support all wrong?

    Read the article

  • VB.NET - Find a Substring in an ArrayList, StringCollection or List(Of String)

    - by CJM
    I've got some code that creates a list of AD groups that the user is a member of, with the intention of saying 'if user is a member of GroupX then allow admin access, if not allow basic access'. I was using a StringCollection to store this list of Groups, and intended to use the Contains method to test for membership of my admin group, but the problem is that this method only compares the full string - but my AD groups values are formatted as cn=GroupX, etc.... I want to be easily able to determine if a particular substring (i.e. 'GroupX') appears in the list of groups. I could always iterate through the groups check each for a substring representing my AD group name, but I'm more interested in finding out if there is a 'better' way. Clearly there are a number of repositories for the list of Groups, and it appears that Generics (List(Of String)) are more commonly preferred (which I may well implement anyway) but there is no in-built means of checking for a substring using this method either. Any suggestions? Or should I just iterated through the list of groups?

    Read the article

  • Having Issue with Bounded Wildcards in Generic

    - by Sanjiv
    I am new to Java Generics, and I'm currently experimenting with Generic Coding....final goal is to convert old Non-Generic legacy code to generic one... I have defined two Classes with IS-A i.e. one is sub-class of other. public class Parent { private String name; public Parent(String name) { super(); this.name = name; } } public class Child extends Parent{ private String address; public Child(String name, String address) { super(name); this.address = address; } } Now, I am trying to create a list with bounded Wildcard. and getting Compiler Error. List<? extends Parent> myList = new ArrayList<Child>(); myList.add(new Parent("name")); // compiler-error myList.add(new Child("name", "address")); // compiler-error myList.add(new Child("name", "address")); // compiler-error Bit confused. please help me on whats wrong with this ?

    Read the article

  • Can someone explain the declaration of these java generic methods?

    - by Tony Giaccone
    I'm reading "Generics in the Java Programming Language" by Gilad Bracha and I'm confused about a style of declaration. The following code is found on page 8: interface Collection<E> { public boolean containsAll(Collection<?> c); public boolean addAll(Collection<? extends E> c); } interface Collection<E> { public <T> boolean containsAll(Collection<T> c); public <T extends E> boolean addAll(Collection<T> c); // hey, type variables can have bounds too! } My point of confusion comes from the second declaration. It's not clear to me what the purpose the <T> declaration serves in the following line: public <T> boolean containsAll(Collection<T> c); The method already has a type (boolean) associated with it. Why would you use the <T> and what does it tell the complier? I think my question needs to be a bit more specific. Why would you write: public <T> boolean containsAll(Collection<T> c); vs public boolean containsAll(Collection<T> c); It's not clear to me, what the purpose of <T> is, in the first declaration of containsAll.

    Read the article

  • C# Multiple constraints

    - by John
    I have an application with lots of generics and IoC. I have an interface like this: public interface IRepository<TType, TKeyType> : IRepo Then I have a bunch of tests for my different implementations of IRepository. Many of the objects have dependencies on other objects so for the purpose of testing I want to just grab one that is valid. I can define a separate method for each of them: public static EmailType GetEmailType() { return ContainerManager.Container.Resolve<IEmailTypeRepository>().GetList().FirstOrDefault(); } But I want to make this generic so it can by used to get any object from the repository it works with. I defined this: public static R GetItem<T, R>() where T : IRepository<R, int> { return ContainerManager.Container.Resolve<T>().GetList().FirstOrDefault(); } This works fine for the implementations that use an integer for the key. But I also have repositories that use string. So, I do this now: public static R GetItem<T, R, W>() where T : IRepository<R, W> This works fine. But I'd like to restrict 'W' to either int or string. Is there a way to do that? The shortest question is, can I constrain a generic parameter to one of multiple types?

    Read the article

  • Serialization of generic types - GWT

    - by sarav
    I have an interface like this public interface IField<T> extends IsSerializable { public String getKey(); public void setKey(String name); public T getValue(); public void setValue(T role); } And a class like this public class FieldImpl<T> implements IField<T> { private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } private T value; public FieldImpl() { } public FieldImpl(String key, T value) { super(); this.key = key; this.value = value; } } When I try to compile I'm getting [ERROR] In order to produce smaller client-side code, 'Object' is not allowed; please use a more specific type (reached via server.sdk.model.IField) What is the cause for this? Is there any place I can read about GWT's generics support?

    Read the article

  • C# Convert string to nullable type (int, double, etc...)

    - by Nathan Koop
    I am attempting to do some data conversion. Unfortunately, much of the data is in strings, where it should be int's or double, etc... So what I've got is something like: double? amount = Convert.ToDouble(strAmount); The problem with this approach is if strAmount is empty, if it's empty I want it to amount to be null, so when I add it into the database the column will be null. So I ended up writing this: double? amount = null; if(strAmount.Trim().Length>0) { amount = Convert.ToDouble(strAmount); } Now this works fine, but I now have five lines of code instead of one. This makes things a little more difficult to read, especially when I have a large amount of columns to convert. I thought I'd use an extension to the string class and generic's to pass in the type, this is because it could be a double, or an int, or a long. So I tried this: public static class GenericExtension { public static Nullable<T> ConvertToNullable<T>(this string s, T type) where T: struct { if (s.Trim().Length > 0) { return (Nullable<T>)s; } return null; } } But I get the error: Cannot convert type 'string' to 'T?' Is there a way around this? I am not very familiar with creating methods using generics.

    Read the article

  • How to use interfaces in exception handling

    - by vikp
    Hi, I'm working on the exception handling layer for my application. I have read few articles on interfaces and generics. I have used inheritance before quite a lot and I'm comfortable with in that area. I have a very brief design that I'm going to implement: public interface IMyExceptionLogger { public void LogException(); // Helper methods for writing into files,db, xml } I'm slightly confused what I should be doing next. public class FooClass: IMyExceptionLogger { // Fields // Constructors } Should I implement LogException() method within FooClass? If yes, than I'm struggling to see how I'm better of using an interface instead of the concrete class... I have a variety of classes that will make a use of that interface, but I don't want to write an implementation of that interface within each class. In the same time If I implement an interface in one class, and then use that class in different layers of the application I will be still using concrete classes instead of interfaces, which is a bad OO design... I hope this makes sense. Any feedback and suggestions are welcome. Please notice that I'm not interested in using net4log or its competitors because I'm doing this to learn. Thank you Edit: Wrote some more code. So I will implement variety of loggers with this interface, i.e. DBExceptionLogger, CSVExceptionLogger, XMLExceptionLogger etc. Than I will still end up with concrete classes that I will have to use in different layers of my application.

    Read the article

  • I want a function to return a type of the subclass its invoked from

    - by Jay
    I want to have a function defined in a superclass that returns a value of the type of the subclass that is used to invoke the function. That is, say I have class A with a function plugh. Then I create subclasses B and C that extend A. I want B.plugh to return a B and C.plugh to return a C. Yes, they could return an A, but then the caller would have to either cast it to the right subtype, which is a pain when used a lot, or declare the receiving variable to be of the supertype, which loses type safety. So I was trying to do this with generics, writing something like this: class A<T extends A> { private T foo; public T getFoo() { return foo; } } class B extends A<B> { public void calcFoo() { foo=... whatever ... } } class C extends A<C> { public void calcFoo() { foo=... whatever ... } } This appears to work but it looks pretty ugly. For one thing, I get warnings on "class A". The compiler says that A is generic and I should specify the type. I guess it wants me to say "class A". But what would I put in for x? I think I could get stuck in an infinite loop here. It seems weird to write "class B extends A", but this causes no complaints, so maybe that's just fine. Is this the right way to do it? Is there a better way?

    Read the article

  • How do I cast from int to generic type Integer?

    - by Rob Kent
    I'm relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by key and this code, albeit ugly, works for a Boolean but not an Integer, when it blows up with a ClassCastException. Can anyone tell me why this is wrong and maybe help me improve the whole routine (using wildcards?)? public static <T> T getPreference(Class<T> argType, String prefKey, T defaultValue, SharedPreferences sharedPreferences) { ... try { if (argType == Boolean.class) { Boolean def = (Boolean) defaultValue; return argType.cast(sharedPreferences.getBoolean(prefKey, def)); } else if (argType == Integer.class) { Integer def = (Integer) defaultValue; return argType.cast(sharedPreferences.getInt(prefKey, def)); } else { AppGlobal.logWarning("getPreference: Unknown type '%s' for preference '%s'. Returning default value.", argType.getName(), prefKey); return defaultValue; } } catch (ClassCastException e) { AppGlobal.logError("Cast exception when reading pref %s. Using default value.", prefKey); return defaultValue; } } I've tried various ways - using the native int, casting to an Integer, but nothing works.

    Read the article

  • Why can't I pass an object of type T to a method on an object of type <? extends T>?

    - by Matt
    In Java, assume I have the following class Container that contains a list of class Items: public class Container<T> { private List<Item<? extends T>> items; private T value; public Container(T value) { this.value = value; } public void addItem(Item item) { items.add(item); } public void doActions() { for (Item item : items) { item.doAction(value); } } } public abstract class Item<T> { public abstract void doAction(T item); } Eclipse gives the error: The method doAction(capture#1-of ? extends T) in the type Item is not applicable for the arguments (T) I've been reading generics examples and various postings around, but I still can't figure out why this isn't allowed. Eclipse also doesn't give any helpful tips in its proposed fix, either. The variable value is of type T, why wouldn't it be applicable for ? extends T?.

    Read the article

  • What else I must do allow my method to handle any type of objects

    - by NewHelpNeeder
    So to allow any type object I must use generics in my code. I have rewrote this method to do so, but then when I create an object, for example Milk, it won't let me pass it to my method. Ether there's something wrong with my generic revision, or Milk object I created is not good. How should I pass my object correctly and add it to linked list? This is a method that causes error when I insert an item: public void insertFirst(T dd) // insert at front of list { Link newLink = new Link(dd); // make new link if( isEmpty() ) // if empty list, last = newLink; // newLink <-- last else first.previous = newLink; // newLink <-- old first newLink.next = first; // newLink --> old first first = newLink; // first --> newLink } This is my class I try to insert into linked list: class Milk { String brand; double size; double price; Milk(String a, double b, double c) { brand = a; size = b; price = c; } } This is test method to insert the data: public static void main(String[] args) { // make a new list DoublyLinkedList theList = new DoublyLinkedList(); // this causes: // The method insertFirst(Comparable) in the type DoublyLinkedList is not applicable for the arguments (Milk) theList.insertFirst(new Milk("brand", 1, 2)); // insert at front theList.displayForward(); // display list forward theList.displayBackward(); // display list backward } // end main() } // end class DoublyLinkedApp Declarations: class Link<T extends Comparable<T>> {} class DoublyLinkedList<T extends Comparable<T>> {}

    Read the article

  • How do you create a generic method in a class?

    - by Seth Spearman
    Hello, I am really trying to follow the DRY principle. I have a sub that looks like this? Private Sub DoSupplyModel OutputLine("ITEM SUMMARIES") Dim ItemSumms As New SupplyModel.ItemSummaries(_currentSupplyModel, _excelRows) ItemSumms.FillRows() OutputLine("") OutputLine("NUMBERED INVENTORIES") Dim numInvs As New SupplyModel.NumberedInventories(_currentSupplyModel, _excelRows) numInvs.FillRows() OutputLine("") End Sub I would like to collapse these into a single method using generics. For the record, ItemSummaries and NumberedInventories are both derived from the same base class DataBuilderBase. I can't figure out the syntax that will allow me to do ItemSumms.FillRows and numInvs.FillRows in the method. FillRows is declared as Public Overridable Sub FillRows in the base class. Thanks in advance. EDIT Here is my end result Private Sub DoSupplyModels() DoSupplyModelType("ITEM SUMMARIES",New DataBlocks(_currentSupplyModel,_excelRows) DoSupplyModelType("DATA BLOCKS",New DataBlocks(_currentSupplyModel,_excelRows) End Sub Private Sub DoSupplyModelType(ByVal outputDescription As String, ByVal type As DataBuilderBase) OutputLine(outputDescription) type.FillRows() OutputLine("") End Sub But to answer my own question...I could have done this... Private Sub DoSupplyModels() DoSupplyModelType(Of Projections)("ITEM SUMMARIES") DoSupplyModelType(Of DataBlocks)("DATA BLOCKS") End Sub Private Sub DoSupplyModelType(Of T as DataBuilderBase)(ByVal outputDescription As String, ByVal type As T) OutputLine(outputDescription) dim type as New T(_currentSupplyModel,_excelRows) type.FillRows() OutputLine("") End Sub Is that right? Does the New T() work? Seth

    Read the article

  • Data Annotations validation Built into model

    - by Josh
    I want to build an object model that automatically wires in validation when I attempt to save an object. I am using DataAnnotations for my validation, and it all works well, but I think my inheritance is whacked. I am looking here for some guidance on a better way to wire in my validation. So, to build in validation I have this interface public interface IValidatable { bool IsValid { get; } ValidationResponse ValidationResults { get; } void Validate(); } Then, I have a base class that all my objects inherit from. I did a class because I wanted to wire in the validation calls automatically. The issue is that the validation has to know the type of the class is it validating. So I use Generics like so. public class CoreObjectBase<T> : IValidatable where T : CoreObjectBase<T> { #region IValidatable Members public virtual bool IsValid { get { // First, check rules that always apply to this type var result = new Validator<T>().Validate((T)this); // return false if any violations occurred return !result.HasViolations; } } public virtual ValidationResponse ValidationResults { get { var result = new Validator<T>().Validate((T)this); return result; } } public virtual void Validate() { // First, check rules that always apply to this type var result = new Validator<T>().Validate((T)this); // throw error if any violations were detected if (result.HasViolations) throw new RulesException(result.Errors); } #endregion } So, I have this circular inheritance statement. My classes look like this then: public class MyClass : CoreObjectBase<MyClass> { } But the problem occurs when I have a more complicated model. Because I can only inherit from one class, when I have a situation where inheritance makes sense I believe the child classes won't have validation on their properties. public class Parent : CoreObjectBase<Parent> { //properties validated } public class Child : Parent { //properties not validated? } I haven't really tested the validation in these cases yet, but I am pretty sure that anything in child with a data annotation on it will not be automatically validated when I call Child.Validate(); due to the way the inheritance is configured. Is there a better way to do this?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >