w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Java Reflection/Generic Types for dynamic-like type casting
I don't understand what you are trying to accomplish, but I can tell you how to implement the code fragments you have posted: Firstly, your enum should pass the (bounded) class into the constructor: public enum Type { FLOAT(Float.class), INTEGER(Integer.class); private final Class<T extends Number & Comparable<T>> clazz; Type(Class<T extends Number & Comparable<T>> clazz) { this.clazz = clazz; } } Note that I don't know what you're going to do with that class. Secondly, your method needs to type the method to declare the type of the objects passed in, and you don't need to refer to a class type of your enum, and the method doesn't really have anything to do with the enum either. It can be a static utility method put anywhe

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

Casting between an object of generic type "T" and an object of generic type ">"
Based on the exception, it looks like you're initializing element with new Object[someLength] and doing an unchecked cast to T[]. This is likely happening in ArrayLinearList. The problem is that in this code: element[ pedro ] = maria; element is treated as a Comparable[] at runtime, and an Object[] isn't a Comparable[]. There are many existing posts related to generic array creation, but your issue is interesting because you've thrown inheritance into the mix (with a narrowing of a type parameter's bounds). The best solution seems to be only interacting with element within the ArrayLinearList class. Make it private and expose getters and setters. This should avoid runtime failures like this (which take some thought to avoid when doing unchecked casts like (T[])new Object[someLength]).

Categories : Java

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#

Casting to generic type in C#
I would personally recommend encapsulating your access to the dictionary with a separate singleton class that then wraps your dictionary getters and setters, something like a RepositoryStore class. I'd recommend changing Dictionary<Type, Type> to Dictionary<Type, object>, and then handle the casting within the RepositoryStore; something like so? Update (using Types and Lazy<T>) If you're using .NET 4, you could take full advantage of the Lazy class, and change the dictionary type to be IDictionary<Type, Lazy<object>>. I've amended my original answer to reflect how this might work: class RepositoryStore { private IDictionary<Type, Lazy<object>> Repositories { get; set; } public RepositoryStore() { this.Repositories = new Dic

Categories : C#

Lambda Reflection with generic type (Where(ReflectedLambda))
well, you may have some flaws in your architecture (hard to say with the sample code)... Anyway, you could call your method using reflection. var method = typeof(<Type with the method>).GetMethod("GenerateExpression"); var genericMethod = method.MakeGenericMethod(sourceObjectType.GetType()); var result = genericMethod.Invoke(null, new[]{regName, idEscrit});//null if method is in a static class but I would really look first at architecture.

Categories : C#

Dynamic casting to a generic interface type
No. You cannot cast an expression to a type that is not known at compile time. (By "known", I mean resolvable to a Type whose generic type parameters are closed.) Having said that, I think it may be possible by using the expression API. The idea is that you would build a lambda expression of the type you determined (which can be strongly-typed), compile it, then execute it on your object to perform the cast. If you 100% need to do this, that's the direction I'd look.

Categories : C#

Casting generic type with interface constraint
Wrapper<Foo> needs to be Wrapper<IFoo>. Then you should be able to cast it. And it needs to implement the interface too. The cast below works... I don't think you can cast an objects generic type parameter to a different type (i.e. IWrapper<Foo> to IWrapper<IFoo>). void Main() { var foo = new Wrapper(); var t = foo as IWrapper<IFoo>; t.Dump(); } public interface IFoo {} public class Foo : IFoo {} public interface IWrapper<T> where T : IFoo {} public class Wrapper : IWrapper<IFoo> {}

Categories : C#

Casting Exceptions Using Generic Type Parameters: Right way to do it?
You are trying to recover runtime type information, so yes you'll need Class.cast or similar. As it stands your code can throw a ClassCastException at the caller of getException because you are catching and storing all Exceptions. You may find it better to remove the generics and have the caller use instanceof or similar.

Categories : Java

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

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

Compile-Time Generic Type Mapping without Reflection
Yes dynamic would be the answer. I had the same issue recently where I had to switch repositories based on some values configured in the database. var tableNameWithoutSchema = tableName.Substring(tableName.IndexOf(".", StringComparison.Ordinal) + 1); var tableType = string.Format("Library.Namespace.{0}, Library.Name", tableNameWithoutSchema); var instance = UnitofWork.CreateRepository(tableType, uoW); CreateRepository returns a dynamic type public static dynamic CreateRepository(string targetType, DbContext context) { Type genericType = typeof(Repository<>).MakeGenericType(Type.GetType(targetType)); var instance = Activator.CreateInstance(genericType, new object[] { context }); return instance; } context was needed as I had to pass the context to Generic repository

Categories : C#

Java Reflection getDeclaredMethod() with Generic Class Type
They should be B and Parameter[], since B is the erasure of T and varargs are implemented as arrays: Method method = a.getClass().getDeclaredMethod( "call", B.class, Parameter[].class ); Note that you have a syntax error: <T extends of B> should be <T extends B>. Also note that the method as you're showing it doesn't need to be generic at all. This would work just as well: private void call(B object, Parameter... parameters) { ... }

Categories : Java

asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables}) The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here Also, you had an extra } in the success function. So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so: var someArr = ['el1', 'el2']; JSON.stringify({ 'param1': 1, 'param2': 'two' 'param3': someArr // etc }); JavaScript: var variables = Array(); var i = 0; $('#Div_AdSubmition').find('.selectBox').each(function () { variables[i] = $(this).find('.selected').find(".text").html(); i++; }); $.ajax({ type: 'post', data: JSON.stringify({'a': variables}),

Categories : C#

Supertype casting in generics (Getting the generic supertype of a generic type)
Here is an iterative approach that could solve your problem: public static <T> void iterateOverSupertypes(T input) { Class<?> clazz = input.getClass(); while (clazz.getSuperclass() != null) { clazz = clazz.getSuperclass(); } }

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#

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#

Structural-type casting does not work with String?
Yes, the String is a Java class and doesn't have the mkString method without a little help. It is a limitation of running in the JVM and using it's native String class for speed and compatibility with Java code. The mkString is added to the String on demand, using an implicit conversion to the StringOps. When you cast the name into HasMkString the String->StringOps implicit conversion no longer apply and so you lose all the extra methods. The workaround would be either to replace def f (name: HasMkString) = name.mkString ("-") with def f (name: HasMkString) = if (name.isInstanceOf[String]) name.asInstanceOf[String].mkString ("-") else name.mkString ("-") or not to throw away the type information by explicitly casting to a structural type, e.g def f (name: HasMkString) = name.

Categories : Scala

Use Converted string to class type for casting
//Use this Dictionary to pair the view types and their corresponding ColorEach to set accordingly Dictionary<Type,bool> colorEaches = new Dictionary<Type,bool>(); colorEaches[typeof(DevExpress.XtraCharts.BarDrawOptions)] = true; colorEaches[typeof(DevExpress.XtraCharts.StackedBarSeriesView)] = true; //..... bool value; Type viewType = sser.View.GetType(); if(colorEaches.TryGetValue(viewType,out value)){ //Suppose your `ColorEach` should be present in all the types added to the Dictionary viewType.GetProperty("ColorEach").SetValue(sser.View, value); }else { //your own code }

Categories : C#

Object of type 'System.Reflection.MdFieldInfo' cannot be converted to type 'MyEnum'
I think you need a Field.GetValue here type.GetProperty("St").SetValue(student, type3.GetField("Good").GetValue(instance), null); Type.GetField returns FieldInfo but what you actually need to pass as a parameter is enum value. Note: I assume Good is a field on type3 which is of type Enum StudentType

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

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

Using emitted type as type parameter in Reflection.Emit
You can set the parent type using SetParent: TypeBuilder tb = mb.DefineType("TestAdmin", TypeAttributes.Public); tb.SetParent(typeof(TestUserBase<>).MakeGenericType(tb)); Type theType = tb.CreateType();

Categories : C#

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 can't i pass Dictionary to IEnumerable> as generic type
Because it's a ref parameter. A ref parameter means that the method can assign a new value to the field / variable passed by the caller. Had your code been legal, the method would be able to assign a List<KeyValuePair<string, string>>, which is obviously wrong. You should not use ref parameters.

Categories : C#

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#

Python value conversion to string representation of postgres procedure parameter including type casting
''' >>> py_to_pg([1,2,3]) "'{1,2,3}'::int[]" >>> py_to_pg('Jack Johnson') "'Jack Johnson'::text" >>> py_to_pg([decimal.Decimal(0.3),decimal.Decimal(0.3),decimal.Decimal(0.4)]) "'{0.3,0.3,0.4}'::numeric(5,4)[];" >>> py_to_pg(datetime.datetime(2013,7,7,13,0,0)) "'2013-07-07T13:00:00'::timestamp" >>> py_to_pg(float(0.5)) "0.5::numeric" >>> py_to_pg(5) "5::int" >>> py_to_pg(['a','b','c']) "'{a,b,c}'::text[]" >>> py_to_pg(None) "'NULL'" >>> py_to_pg(33.00) "'33.0000'::numeric(5,4)" >>> py_to_pg(True) "'T'" ''' def py_to_pg(pyval): # set precision to 4 decimals out getcontext().prec = 4 t2t = {int: "'%s'::int",

Categories : Python

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

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

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#

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 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

Cast to a reflected Type in C#
No :-) Case 1: object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();} Foo result = (Foo)objFoo; There is no reflection here, because you know the Foo type at compile time. Case 2: interfaces. Normally the best one... You don't know what exactly MakeFoo returns, but you know it's an IFoo interface... object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();} IFoo result = (IFoo)objFoo; Case 3: you aren't sure MakeFoo returns Foo object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();} if (objFoo is Foo) { Foo result = (Foo)objFoo; } or, similar object objFoo = MakeFoo(); // object MakeFoo(){return new Foo();} Foo foo = objFoo as Foo; if (foo != null) { // use foo } Case 4: type Foo is completely unknown to your program. You don't have a Fo

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

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#

scala convert String to generic type
Take a look at marshalling/unmarshalling as implemented in Spray. You may not need to reinvent the solution, and if you do, you can take a look at their source to see how they've implemented it. Spray's marshalling/unmarshalling is similar to object graph serialization and works with more than just JSON so there's some additional inherent complexity within the implementation. You could also get around manually parsing JSON and try lift-json. lift-json is closer to JSON though through extract it can operate similar to Spray's marshaller/unmarshaller.

Categories : Scala

Type casting using type parameter
That's what a ClassTag if for: import reflect.ClassTag def convert[T : ClassTag](key: String): Option[T] = { val ct = implicitly[ClassTag[T]] someJavaMethod(key) match { case ct(x) => Some(x) case _ => None } } It can be used as an extractor to test and cast to the proper type at the same time. Example: scala> def someJavaMethod(s: String): AnyRef = "e" someJavaMethod: (s: String)AnyRef [...] scala> convert[Int]("key") res4: Option[Int] = None scala> convert[String]("key") res5: Option[String] = Some(e) Edit: note however that a ClassTag does not automatically unbox boxed primitives. So, for example, convert[Int]("a") would never work, because the java method returns AnyRef, it would have to be convert[java.lang.Integer]("a"), and so on for other pri

Categories : Scala

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#



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