w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to declare property as generic type constrained to classes that inherits a base class?
Public Class SomeOtherClass(Of T as {OnlyClassesWhichInherits(ObjectBase)}) Are you perhaps looking for… this? :) Public Class SomeOtherClass(Of T As ObjectBase)

Categories : Dotnet

Contravariance on constrained generic type parameters
Answer to initial question You're currently trying to convert a single element of type TDerived to a sequence of type Base. I wouldn't expect your Cast call to work either, as TDerived doesn't implement IEnumerable - I suspect you've actually got that to work in a different situation instead. I suspect you actually meant: void Test3<TDerived>(IEnumerable<TDerived> derived) where TDerived : Base { IEnumerable<Base> b = derived; } That compiles with no problems. Answer to edited question Okay, now we've got the real problem between two type parameters, the issue is that the compiler doesn't know that they're reference types - which is required for generic variance. You can fix that with a class constraint on TDerived: void Test3<TDerived, TBase>(IEnumerabl

Categories : C#

Passing a class with type parameter as type parameter for generic method in Java
This is actually possible in Java, using some "tricks". Don't succumb to pressure from the C# fanatics! (j/k) The "trick" is to create a class that extends a generic type, and access the value of the type parameter of the parent class through the Type returned by .getGenericSuperclass() or .getGenericInterfaces(). This is quite cumbersome. To simplify our lives, Google has already written most of the boring part of the code for us, and made it available through Guava. Check the TypeToken class, which does exactly what you want. For example: TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() {}; Then you pass around a TypeToken<T> instead of a Class<T> and that's all. It provides you with methods to do reflection on the type repre

Categories : Java

How to get generic type "T" of class when reused in method
This is pretty simple using TypeTools: Class<?> t = TypeResolver.resolveRawArgument(Parent.class, Child.class);

Categories : Java

How can I use a method of the defined type of the generic class?
Change this declaration public class Team<AbstractMember> to public class Team<T extends AbstractMember> Then, in your code you should use T to refer to the class Type. For example, you will have to change the for loop you from for (AbstractMember member : memberList) to for (T member : memberList) {

Categories : Java

Passing class type to generic method at runtime
Try this: AuditTrail auditTrail = new AuditTrail(); var method = auditTrail.GetType().GetMethod("GetActualOldValue"); var genericMethod = method.MakeGenericMethod(auditTrail.GetType()); var result = genericMethod.Invoke(auditTrail, null);

Categories : C#

Java Pass instance type of Object to generic class type parameter
No.. generic type should be known at compile time. Generics are there to catch possible runtime exceptions at compile time itself. List<Integer> list = new ArrayList<Integer>(); //..some code String s = list.get(0); // this generates compilation error because compiler knows that list is meant to store only Integer objects and assigning the value got from list to String is definitely an error. If the generic type was determined at run-time this would have been difficult.

Categories : Java

Generic Method Return Type as Type parameter
Is this what you are looking for? I've added an extra catch for cases where the cast isn't valid also Decimal i = stringName.ToType<Decimal>(); public static T ToType<T>(this string value) { object parsedValue = default(T); try { parsedValue = Convert.ChangeType(value, typeof(T)); } catch (InvalidCastException) { parsedValue = null; } catch (ArgumentException) { parsedValue = null; } return (T)parsedValue; } Edit a shortcut approach to fix Anton's comment if (typeof(T).IsValueType) return default(T);

Categories : C#

Using nested type declared in a generic class within the generic interface that the class is implementing
The only way that you can make this work is to define the procedural type outside of the implementing class. Like this: type IMyIntf<A> = interface; TMyProc<A> = reference to procedure(Intf: IMyIntf<A>); IMyIntf<A> = interface procedure Foo(Proc: TMyProc<A>); end; TMyClass<A> = class(TInterfacedObject, IMyIntf<A>) procedure Foo(Proc: TMyProc<A>); end;

Categories : Delphi

Inherited method returned reference type
One solution is to override the method in the child class and change the return type to a more specific one, ie. the child type. This requires casting. Instead of using the typical (Child) cast, use the Class#cast(Object) method public class Parent { public Parent example() { System.out.println(this.getClass().getCanonicalName()); return this; } } public class Child extends Parent { public Child example() { return Child.class.cast(super.example()); } public Child method() { return this; } } The cast is hidden within the standard method. From the source of Class. public T cast(Object obj) { if (obj != null && !isInstance(obj)) throw new ClassCastException(cannotCastMsg(obj)); return (T) obj; }

Categories : Java

return generic IEnumerable when passing concrete type parameter for a generic method
You cannot convert the Type class to a generic T parameter without using reflection. The parameter also needs to be present as part of the method. Jon Skeet was using type inference by example combined with generics in order to guarantee type safety and simplify the generic code. Unfortunately you will lose that type safety using Type and reflection. private IEnumerable<EntityObject> GetFilteredData(Type entityType, SortedList<string, string> filterList, List<int> weeks) { var method = typeof(<class>).GetMethod("GetFilteredDataImpl"); var generic = method.MakeGenericMethod(entityType); return (IEnumerable<EntityObject>)generic.Invoke(this, new[] {

Categories : C#

Late-Binding Exception Calling Generic Method of Generic Type in C#
Your GetFirstGenericArgument() is wrong. Calling GetGenericTypeDefinition() returns the underlying open generic type. Its type argument is T. Instead, you should write t.GetGenericArguments()[0], which will get the value of the generic type parameter for the closed type. No; your code doesn't make any sense. What on earth are you trying to do? I suspect that you actually want to write public class CollectionHandler<T> { public void Handle(IEnumerable<T> collection) { // Look ma, no reflection! } }

Categories : C#

Reflection - Navigate a non-generic method from a generic type definition to a concrete one
You can use the MakeGenericType method, like this: m.DeclaringType.MakeGenericType(typeof(int)) and then probably GetMethod again if you really want to go this way: m.DeclaringType.MakeGenericType(typeof(int)).GetMethod("Method"); However, consider Jon Skeet's comment for simpler solution.

Categories : C#

Concretize data type in inherited class
As Sotirios already commented, generics would do some good here: public interface DataFiller<T extends Container> { void fillContainer(Object param1, Object param2, T container); } public class InOrderDataFiller implements DataFiller<InOrderContainer> { @Override public void fillContainer(Object param1, Object param2, InOrderContainer container) { container.setContent1(param1); container.setContent2(param2); } } public class ReverseDataFiller implements DataFiller<ReverseContainer> { @Override public void fillContainer(Object param1, Object param2, ReverseContainercontainer container) { container.setContent1(param2); container.setContent2(param1); } } You could also introduce generics for the parameter types

Categories : Java

Create instance of generic type in Java within the generic class
Due to implementation of generics in Java you must pass the Class<T> object for the further use. Here is the example: public class Outer<E> { private static class Inner<E> { E createContents(Class<E> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { return null; } } } private Class<E> clazz; private Inner<E> inner; public Outer(Class<E> clazz) { this.clazz = clazz; this.inner = new Inner<>(); } public void doSomething() { E object = inner.createContents(clazz); System.out.println(object); } } Also you can use <? extends E>, p

Categories : Java

Modifying value type in generic class implementing generic interface C#
You are trying to add 10 (an integer) to a value of type T. T can be an integer, or a DateTime, or a List, or some other custom class. This means that there is absolutely no guarantee that your T will be able to add itself to an integer. Unfortunately, there is no way in C# to add a generic type constraint that will restrict the parameter to a type that will support a certain operation. There are workaround, but they are ugly. i.e. you could have: class Point<T>{ ... } and then have class IntPoint : Point<int>, IDoable<int> { ... } class DoublePoint : Point<double>, IDoable<Double> { ... }

Categories : C#

Type Erasure - Extending Java Generic Class To Be Non-Generic
Yes, IntegerList is a reified type, which is what I think you're trying to say. And while we are at it, ArrayList is also a reified type, which means you can do the same things with ArrayList that you can do with IntegerList. (But not with ArrayList<Integer>, which is not a reified type.)

Categories : Java

How to declare an inter-type method with return type of every object's class?
Try this: aspect MyAspect { public S MyInterface<S>.getMyself() { return (S) this; } } interface MyInterface<T extends MyInterface<T>> { } class MyClassOne implements MyInterface<MyClassOne> {} class MyClassTwo implements MyInterface<MyClassTwo> {} class Main { public static void main(String[] args) { MyClassOne aClassOne = new MyClassOne().getMyself(); MyClassTwo aClassTwo = new MyClassTwo().getMyself(); MyClassOne errorClassOne = new MyClassTwo().getMyself(); // compile error MyClassTwo errorClassTwo = new MyClassOne().getMyself(); // compile error } } Fun with generics! Answer is straight forward, I think, but let me know if this is confusing for you.

Categories : Java

Why isn't a generic type recognized as its derived type when passed as a generic parameter?
It is because you have list of Predicates. When you get element from list it is still only a base class. In runtime it will be a derived class, but generic works durring compilation.

Categories : C#

Check if a type implements a generic interface without considering the generic type arguments
As far as I know, the only way to do this is to get all interfaces and see if the generic definition matches the required interface type. bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()) .Contains(typeof(MyInterface<,>)); EDIT: As Jon points out in the comments, you could also do: bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));

Categories : C#

Calling Base Class Functions with Inherited Type
The functionality you want is in the base class, but it returns a base class (which makes sense since the Coord3D has no idea what a Vector3D is). If you are adamant about not rewriting operator+() for Vector3D (which I think is fair if you plan to have multiplication and such as well), you can instead create a copy constructor in the Vector3D class that can construct a Vector3D from the Coord3D result. class Vector3D: public Coord3D { public: Vector3D (float a = 0.0f, float b = 0.0f, float c = 0.0f) : Coord3D (a, b, c) {}; Vector3D (const Coord3D& param){ new ((Coord3D*)this) Coord3D(param); } }; int main () { Vector3D a (3, 4, 5); Vector3D b (6, 7, 8); Vector3D c = a + b; cout << typeid(c).name(); Sleep(1000);

Categories : C++

Query on Junit @parameters method's return type and the test class constructor argument type
As you suggested the values are being casted. The casting is actually done by the Java reflection API, specifically: Constructor.newInstance(Object...). If you're curious, the above method is invoked by JUnit on line 186, here (JUnit v4.11 source).

Categories : Java

Scala Type Mismatch underlying type and class vs method
The problem in your code is type parameter shadowing. You have: class ThreeStacks[A, B, C](val stackSize:Int = 1000) { def push1[A](value: A): Unit = stack1.push(value) ... } It should be: class ThreeStacks[A, B, C](val stackSize:Int = 1000) { def push1(value: A): Unit = stack1.push(value) ... } The way you have done it, type parameter A of class ThreeStacks and type parameter A of method push1 are completely different ones and thus, are incompatible with each other. The same applies to B and C.

Categories : Scala

Generic type conversion in generic method
You seem to hope that the class called NetworkEventBase<T> would be covariant in T. But generic classes can't be covariant in C# (generic interfaces can). See other threads on this issue.

Categories : C#

What is the benefit of extending a generic by specifying the new type as actual type of generic
You might do something like this when dealing with recursive data structures. For example, nodes in a graph or a tree could be defined as a collection of other nodes: class Node extends AbstractList<Node> { ... } Equally you might see something like this if the abstract/generic type is meant for comparing objects of a similar type, such as is the case with java.lang.Comparable: class MyObject implements Comparable<MyObject> { public int compareTo(MyObject other) { ... } }

Categories : Java

Find method parameter type or parameter generic type
Please try using below code, you have to compare type and Integer.class public static void main(String[] args) throws ClassNotFoundException { Class<?> clazz = Class.forName("Test"); Class<Integer> lookingForClass = Integer.class; Method[] method = clazz.getMethods(); for (int i = 0; i < method.length; i++) { Type[] types = method[i].getParameterTypes(); for (int j = 0; j < types.length; j++) { Type type = types[j]; Class<?> result = type.getClass(); if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] fieldArgTypes = pt.getActualTypeArgume

Categories : Java

How to make Generic Type as out type if it is reference Type?
If you have an error with the return type of IEnumerable<IGrouping<string, MyClass>> in a generic class that has been declared using <T>, then I'm guessing that your return type should actually be IEnumerable<IGrouping<string, T>>... of course, without seeing your code, this can only be a guess.

Categories : C#

Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?
Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type? A is a raw type. That's a type with all generics dropped in the API dropped, even ones with fixed type arguments. See the JLS section 4.8 and the Raw Types section of the Java Generics FAQ for more information. In this case, if you want any A, you can use a wildcard: public static void test(A<?> i)

Categories : Java

Generic method with return type
Due to type erasure, you will never know the type of E unless you either get E, Foo<E>, or Class<E> from E.class passed in. The type is not available at runtime in this case. A cast may also become illegal, but we can't even get that far. Passing in a boxed Integer gives a refiable argument, so you know the type must be Integer, and the boxed integer is thus returned. Either genericize the Demo class so E is refiable, or make sure something that tells what E is (being refiable) is passed in, such as the Foo<E>, a Class<E> being populated with E.class or an example of E itself.

Categories : Java

Invoke method on generic type?
Your code produces a compilation error because the compiler has no way of knowing that T has a method named Add that receives a single string parameter. I thought that generic types in Delphi was simply inserted into the generic function, so it would only error out if used with a type which don't have an Add(string) method. If you were using Smalltalk or C++ templates, then your assumption would be accurate. However, generics are not the same as templates. For generics you need to apply a constraint to the type parameter. The constraint needs to tell the compiler what properties T must have. For example, you could constrain T to be derived from a class that has a suitable Add method. Or you could constrain T to implement an interface with a suitable Add method. Documentation link

Categories : Delphi

How to use a generic type parameter as type parameter for a property declared as an interface with type constraints?
Try to add class constraint to the TItem: namespace Sample2 { public interface IInterfaceContainer<T1, T2> where T1 : T2 { } public interface IInterfaceParent { } public interface IInterfaceChild : IInterfaceParent { } public class ClassSampleDoesNotWork<TItem> where TItem : class, IInterfaceParent { IInterfaceContainer<IEnumerable<TItem>, IEnumerable<IInterfaceParent>> SomeProperty { get; set; } } } This works because variance only works for reference-types (or there is an identity conversion). It isn't known that TItem is reference type, unless you add : class. Read this article for more information. Here is a sample code to demonstrate this behavior: IEnumerable<Object> ite

Categories : C#

Java generic method type casting
This works perfect, nothing special, normal use of generics gt.<String>echoV(); //this line works well Here do we have something less obvious. Because generic method are defined at runtime does the jvm not know what kind of Class the generic method will return at compiletime, hence the classTypeException gt.<String>echoV().getClass();//this line leads to a type cast exception you should allocated it to a variable first, because the jvm does know the type of the variable at compiletime String s = gt.<String>echoV(); s.getClass();

Categories : Java

How to introduce a generic type into a class?
This refactoring should be named "Introduce generic parameter", but I am not sure if any tool does that. You can write a visitor using NRefactory to rewrite the code, but it will not by default give you a great resolution of all referencing places. Maybe try writing a ReSharper plugin?

Categories : C#

how to check the Type used by a generic class
As far as I can tell, there is no simple way to is-check a generic class; likely due to the flexibility of the generic parameter. Here is a solution: public static bool IsExceptionBoundToType(FaultException fe, Type checkType) { bool isBound = false; // Check to see if the FaultException is a generic type. Type feType = fe.GetType(); if (feType.IsGenericType && feType.GetGenericTypeDefinition() == typeof(FaultException<>)) { // Check to see if the Detail property is a class of the specified type. PropertyInfo detailProperty = feType.GetProperty("Detail"); if (detailProperty != null) { object detail = detailProperty.GetValue(fe, null); isBound = checkType.IsAssignableFrom(detail.GetType()); } } return (is

Categories : C#

Cast generic type T into Class
You could do this: public class Parent<T> { private final Class<T> clazz; public Parent(Class<T> clazz) { this.clazz = clazz; } public Class<T> getType() { return clazz; } } public class Foo<T> extends Parent { public Foo(Class<T> clazz) { super(clazz); } }

Categories : Java

How to get a class from a bounded generic type
Try declaring enumerationClass as: val enumerationClass: Class[T] = m.runtimeClass.asInstanceOf[Class[T]] You already know that the the runtimeClass of the Manifest is of type T, so I'm not sure why you were declaring it as val enumerationClass: Class[_ <: Enum[T]]. The Enum.valueOf can not work with a wildcarded type so that's why you were seeing that error.

Categories : Scala

Getting a generic type of implementing class
Well you could write implements Cloneable, but then you'd be using the raw type, which is generally a bad idea. For the sake of stronger typing, you're better off sticking with what you've got.

Categories : Java

Get generic type class in superclass with GWT
I would pass it through the constructor: public class SuperClass<T> { private Class<T> type; public SuperClass (Class<T> type) { this.type= type; } public void Class<T> getClassType() { return type; } } There are third party libraries for this: https://github.com/jhalterman/typetools There is no other way to get it in the runtime because java generics are a compile time feature.

Categories : Java

create a generic class for the type name
There's three parts to this: getting the Type from the string "Game" creating the generic instance doing something useful with it The first is relatively easy, assuming you know a bit more - for example, that Game is in a particular assembly and namespace. If you know some fixed type in that assembly, you could use: Type type = typeof(SomeKnownType).Assembly .GetType("The.Namespace." + nameEntity); (and check it doesn't return null) Then we need to create the generic type: object repo = Activator.CreateInstance( typeof(Repository<,>).MakeGenericType(new[] {typeof(long), type})); however, note that this is object. It would be more convenient if there was a non-generic interface or base-class that you could use for Repository<,> - I would put serious though

Categories : C#

Get Class Type using typeof if Class has generic arguement
Would this work? Yes (assuming you add the proper semi-colon at the end of your line, and assign the resulting value to a System.Type variable). For example, given: Type genericType = typeof(System.Int32); Type fullType = typeof(test<>).MakeGenericType(new Type[] { genericType }); Console.WriteLine(fullType); This will print: MyNamespace.test`1[System.Int32] Which is the proper type name for the fully qualified type.

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.