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

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#

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

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#

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

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

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#

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#

Scala: Declaring method with generic type parameter
I. Very close to what you want: def readValue[T:ClassTag](s:String):T = { val tClass = implicitly[ClassTag[T]].runtimeClass //implementation for different classes. } usage is a bit clearer than in Java: val myDouble = readValue[Double]("1.0")

Categories : Scala

Extension method with generic Func parameter of other type
Look at this: s => s.Length; How's the compiler suppose to know whether or not s is a string or s is an array or some other type that has a Length property? It can't, unless you give it some information: (string s) => s.Length; Oh, there we go. So now, try this: myFirstObject.Extension((myOtherObject o) => o.Prop > 2 && o.Prop < 15); That will work, because you've told the compiler what it should use for TIn, and it can figure out what to use for TKey based on the expression.

Categories : Linq

Why does method type inference fail to infer a type parameter?
Your problem is caused by the fact that constraints are not considered part of the signature and are never used to make deductions during type inference. You are expecting the inference to go: TEnumerable is determined by taking the type of the first argument. TElement is determined by taking the IList<T> implementation information from TElement TProperty is determined by the type of the body of the lambda But C# never makes that second step because that requires considering information from a constraint. As you note, if you provide that information in the lambda then the compiler makes the deduction based on the formal parameter type. Fortunately your constraint is completely unnecessary. Rewrite your method to have a simpler signature that doesn't have a constraint: void Ass

Categories : C#

Method with Type (x) parameter returning Type x
Assuming I've read your question correctly, all you should need is: public T GetSomething<T> { return default(T); } DateTime dt = GetSomething<DateTime>();

Categories : C#

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

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#

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#

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#

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

Java generic method parameter type inside brackets vs. outside brackets
The first one should be used if you just care that findMax accepts a list that meets certain criteria (in your case a List of type that extends Number). static Number findMax(LinkedList<? extends Number> list) { Number max = list.get(0); for (Number number : list) { if (number > max) { max = number; } } return max; } This method returns Number. For example, this might be a problem if you have a class of your own that extends Number and has some special methods that you would like to use later on the result of this method. The second one should be used when you plan to use exact type T in the method body, as a method parameter or as a return type of the method. static <T extends Number> T findMax(LinkedList<T> list, T c

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

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

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

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

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#

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#

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#

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#

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#

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



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