w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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#

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#

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

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

How to return correct type from generic function passed a related abstract type parameter
I am just going to reiterate my own (current) "answer" for my question, because I thought it would be interesting/instructive to allow readers to vote it up or down to generate a more direct comparison with answers provided by others. trait Context { // ... other stuff ... protected val aList: List[A] protected val bList: List[B] protected val cList: List[C] def get[R <: Referenced](ref: R#refType): Option[R] = { val result = ref match { case aRef: ARef => aList.find(_.ref == aRef) case bRef: BRef => bList.find(_.ref == bRef) case cRef: CRef => cList.find(_.ref == cRef) case _ => throw new RuntimeException("Unknown Ref type for retrieval: "+ref) } result.asInstanceOf[Option[R]] } }

Categories : Scala

Java type parameter is hiding a generic type?
Try this: public abstract class BaseWidgetProcessor<COMMAND> { protected Widget<COMMAND> widget; public BaseWidgetProcessor(Widget<COMMAND> widget) { this.widget = widget; } // presumably uses widget public abstract COMMAND process(); }

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#

Generic inference of type parameter with constraint to other type parameter
You can't infer just some type parameters within a method call. Generic type inference either infers all type parameters, or none. There's no way of inferring THost from the parameters (there could be multiple classes which derive from HostBase<Config>), which means you basically can't use type inference for that method. Looking at this specific example, I think you're going to find it tricky to use type inference at all, because of the way the relationships work.

Categories : C#

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

Java generics and casting a generic type
You need to do a double cast: return (Function<Reference<T>, T>)(Function<?, ?>)ToData.INSTANCE; See also my recent answer using this pattern (from Joshua Bloch's Effective Java item 27, "favor generic methods") as an example of a valid unchecked cast. As I point out there, you should also consider suppressing the unchecked cast warning: @SuppressWarnings("unchecked") // this is safe for any T final Function<Reference<T>, T> withNarrowedTypes = (Function<Reference<T>, T>)(Function<?, ?>)ToData.INSTANCE; return withNarrowedTypes;

Categories : Java

How do I get type parameter from type with type parameter, inside scala macro?
You can use the TypeRef extractor: import reflect.runtime.universe._ // or in a macro "c.universe._" val tpe = weakTypeOf[List[Int]] // extract type parameters val TypeRef(_,_, tps) = tpe // tps has type List[Type] println(tps.head) // Int

Categories : Scala

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

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#

How Generics allows strong type checking for Type Casting errors during Compile Time
JPA makes use of generics in TypedQuerys to ensure that the expected type is returned. If you ask for a Customer, the type system knows to treat the results of the query as Customer objects and not as a plain Object you have to cast yourself, and if you use the Criteria API, it can also verify that your query parameters refer to valid attributes of the Customer class.

Categories : Java

Does type erasure of Java Generics cause full type casting?
The type-checking is done at compile-time. If you do this: List<Cheesecake> list = new ArrayList<Cheesecake>(); then the generic types can be checked at compile-time. This erases to: List list = new ArrayList(); which is no different to any other up-cast (e.g. Object o = new Integer(5);).

Categories : Java

Generics Bounded Type Parameter
You're allowed to make an overriding method's return type more specific due to return type covariance, but you can't change the method's parameters without changing its signature. That's why the compiler complains that you haven't implemented get(Query<TypeA>) when you change it to get(SomeQuery). You'll need to make Service more flexible in order to get what you want: interface Service<T extends BaseType, Q extends Query<T>> { public Result<T> get(Q query); } class SomeService implements Service<TypeA, SomeQuery> { @Override public SomeResult get(SomeQuery query) { ... } } Also note that the narrowed return type doesn't matter when coding to interface: when SomeService is typed as Service<TypeA, SomeQuery>, get will still re

Categories : Java

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#

Java generics: Use this type as return type?
The problem is that the method setX() returns object of class A and you are trying to write it to an object of class B. It can be done vice-versa without casting (A a = new B();), but this way you have to cast it because the statement B b = new B().setX(); is similar to B b = new A(); which can't be done.

Categories : Java

Using a generic type argument in place of an argument of type System.Type. Is it a smell?
Methods that deal with types usually do just that: Dealing with types. IMO, Class.Method<SomeType>(); is much better than Class.Method(typeof(SomeType)); But that is a matter of opinion I guess. Consider LINQ's .OfType<T>(), for example: personlist.OfType<Employee>().Where(x => x.EmployeeStatus == "Active"); versus: personlist.OfType(typeof(Employee)).Where(x => ((Employee)x).EmployeeStatus == "Active"); which one would you prefer?

Categories : C#

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#

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

How can i make a generic function of two functions with a generic type specifier to a parameter
public class BinarySearchComparers<T> : IComparer<KeyValuePair<int, T>> // Declares a generic type { public int Compare(KeyValuePair<int, T> x, KeyValuePair<int, T> y) { return x.Key.CompareTo(y.Key); } } Is it what you want? Update Given Chris Sinclair understanding of your question, the solution might be: public class BinarySearchComparers<U, T> : IComparer<KeyValuePair<U, T>> // Declares a generic type where U : IComparable<U> // Restricts the type U to implémentations of IComparable<U> (necessary to call CompareTo) { public int Compare(KeyValuePair<U, T> x, KeyValuePair<U, T> y) { return x.Key.CompareTo(y.Key); } }

Categories : C#

Generic Type x Generic Parameter: Building a "very generic" structure
Well, first of all, you're overcomplicating this. All you really need to do is: public void add(final Tree<? extends T> subTree) { Theres no need to parameterize add(). But anyways, I'll address your original attempt: You want SubTree extends Tree<Leaf>, because even if Leaf extends T you can't guarantee that SubTree extends Tree<T> with SubTree<Leaf> matches. E.g. if your class hierarchy is: public class Base { } public class A extends Base { } public class B extends Base { } If Leaf is A and SubTree is Tree<B> then add (final SubTree<Leaf>) does not match Tree<B>. So conceptually you actually want this: public <Leaf extends T, SubTree extends Tree<Leaf>> void add(final SubTree<Leaf> subTree) { Of course that is not va

Categories : Java

Create instance of generic type in Java when parameterized type passes through hierarchies?
getClass().getGenericSuperclass(); gives you the details of the super class. Therefore it will only work if you subclass a parameterized super class. It won't work if you instantiate a parameterized super class given type parameters.

Categories : Java

Create instance of generic type in Java when parameterized type is contained?
The anonymous class must have the actual type parameter hard-coded in its declaration for it to work. new Parameterized<E>(){}; does not work. You are just hard-coding "E" (a type variable). So when you look at the metadata using reflection all you see is "E" (a type variable). You must create a subclass which hard-codes its superclass with an actual class as type argument at compile-time: new Parameterized<String>(){}; I tried to adapt Steve B's approach of creating an anonymous subclass: You missed the whole point of that. The point was not to create a subclass. The point was to create a subclass with the actual class of the type argument hard-coded in the superclass.

Categories : Java

Inferred type is not a valid substitute for a Comparable generic type
Actually more detailed explanation of this error gives your javac itself: java: no suitable method found for sort(java.util.ArrayList<MyItem<V>>) method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable (cannot instantiate from arguments because actual and formal argument lists differ in length) method java.util.Collections.<T>sort(java.util.List<T>) is not applicable (inferred type does not conform to declared bound(s) inferred: MyItem<V> bound(s): java.lang.Comparable<? super MyItem<V>>) So, the main question is: why is method Collections.<T>sort(java.util.List<T>)) not applicable? The answer is: because in Collections.<T>sort(java.util.List<

Categories : Java

Autofac - Returning Concrete Type For Abstract Generic Type
After struggling to find a way of integrating Steven's solution with Autofac, I came across Patrick Desjardin's blog post: The three layers of validation (Controller, Service & Repository). I found it easy as you don't have to inject any Validation Providers. Also, it is easy to be integrated with any layer. Please make sure you read the follow up posts as well: How to validate model object with Asp.Net MVC correctly Model validation and Entity Framework 4.3 Any opinions that compares both solutions would be much appreciated. Many thanks!

Categories : C#

Get actual type of generic type argument on abstract superclass
Common way to sort this issue in a secure way is to add a constructor to store the class of the type. Example in your context: public abstract class BaseDao<T extends PersistentObject> { private Class<T> classT; BaseDao(Class<T> classT){ this.classT=classT; } protected Class<T> getClazz() { return classT; } // ... }

Categories : Java

How do I resolve the actual type for a generic return type using reflection?
At runtime, it returns Object because of type-erasure which replaces all generic types with Object. There is no way to determine at runtime what generic type was provided at compile-time. type-erasure

Categories : Java

Forcing type parameter to implement specific method in java generics
You could make an abstract base class called ItemBase, make equals abstract and then have Item extend ItemBase. public abstract class ItemBase { @Override public abstract boolean equals(Object o); } public class Bag extends ItemBase This would force anyone Implementing ItemBase to specifically implement equals

Categories : Java

Get generic type from parameter
Try this Edit: It would only work for Type T. public object[] LoadIt<T>(KeyValuePair<T,string>[] resources, ContentManager content) { object[] result = new object[resources.Length]; for(int i=0;i<result.Length;i++) { result[i] = content.Load<T>(resources[i].Value); } return result; }

Categories : C#

How to get the Generic Type Parameter?
Java has a misguided feature called Type Erasure that specifically prevents you from doing that. Generic parameter information does not exist at runtime. Instead, you can manually accept a Class<T>.

Categories : Java

Cant declare an instance with type parameter that is one layer off the constraint of the type parameter
Since TypedTableBase is generic, when you use it, you have to specify the actual datatype as in public class A<T> where T:DataTable { } public class B :TypedTableBase<DataRow> { } class MyClass { A<B> asdf = new A<B>(); }

Categories : C#

Using weka in C#: Unable to cast object of type 'java.util.ArrayList' to type 'System.Collections.Generic.List`
I am answering my own question. I used this link to solve the problem I was facing. Thanks @SecretSquirrel(see the comments) and @Jon Iles (see the answer I've linked).

Categories : C#

does Java type erasure erase my generic type?
Some Generic type information is stored in Signature attributes . Refer JLS 4.8 and 4.6 and JVM spec 4.3.4. Read here: Probably the most common complaint about generics in Java is that they are not reified - there is not a way to know at runtime that a List<String> is any different from a List<Long>. I've gotten so used to this that I was quite surprised to run across Neil Gafter's work on Super Type Tokens. It turns out that while the JVM will not track the actual type arguments for instances of a generic class, it does track the actual type arguments for subclasses of generic classes. In other words, while a new ArrayList<String>() is really just a new ArrayList() at runtime, if a class extends ArrayList<String>, then the JVM knows that String is the actual t

Categories : Java

Type inference when inheriting generic type and constraint
If you could omit the type parameter, there would be nothing to prevent you from having a single class that implemented both IStringToTypeConverter<Foo> and IStringToTypeConverter<Bar>. If that class did both, which type can it safely infer it should be using as the second type parameter for CustomStringType? Remember: you can only make logical assumptions that the compiler can make, no cheating and using your domain knowledge to resolve the issue! On the other hand, if you flip it and provide just the TransactionStatus type, secretly hoping that reflection will somehow solve your problems, it might be possible that two different classes both implement IStringToTypeConverter<TransactionStatus>. You've still got a problem, you don't know which one is correct for your prob

Categories : C#

C#, instantiating a generic type - with variable type argument?
You can do it with reflection var entryType = typeof(Entry<>); Type[] typeArgs = { o.GetType() }; var genericType = entryType.MakeGenericType(typeArgs); IEntry entry = (IEntry)Activator.CreateInstance(genericType);

Categories : C#

How to switch on generic-type-parameter in F#?
If you want the same logic, you could use if/else's just like C#, or define a map of types to "type converters." But I would probably opt for something simpler, like this: type XElement with member this.Attr<'T>(name) = match this.Attribute(XName.Get name) with | null -> Unchecked.defaultof<'T> | attr -> Convert.ChangeType(attr.Value, typeof<'T>) :?> 'T

Categories : C#

IntelliSense: argument of type "_TCHAR *" is incompatible with parameter of type "const char *"
Your project is configured for Unicode which means that the _TCHAR macro evaluates to wchar_t, which is a 16 bit UTF-16 data type on Windows. But the library you are calling accepts 8 bit char data. So, you will need to make both sides of the interface match. Lots of ways to do that. The obvious options are: Change your project to target ANSI (change the character set to multi byte in the VS project configuration). Convert the input argument from UTF-16 to ANSI before calling the library. It seems to me to be needlessly complex to use _TCHAR these days. That was useful when we needed to support Win9x (no Unicode support) and WinNT (supports Unicode) from a single code base. But I expect that nowadays you are targeting NT based systems and so you are safe to assume support for Unicode

Categories : Visual Studio 2010

Argument type 'lambda expression' is not assignable to parameter type 'System.Action'
I doubt this has anything to do with mvvmcross or mvvm A quick search for this error message suggests this is more likely to be down to tooling - especially r# - eg see hits like: http://devnet.jetbrains.com/thread/292248 http://caliburn.codeplex.com/discussions/212685 http://youtrack.jetbrains.com/issue/RSRP-178647?projectKey=RSRP If you are running any extensions like r# and you remove or disable them, then this may remove the warning. If disabling them helps, then I would recommend asking the extension vendor(s) for support. If disabling them does not help, then I would recommend investigating the differences between the two projects where the problem does/doesn't occur - that will hopefully yield the answer.

Categories : C#



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