Menu
  • HOME
  • TAGS

Get id column name from POJO, using reflection

java,jpa,reflection,annotations

This is the all-by-yourself solution: public static String getPKColumnName(Class<?> pojo) { if (pojo == null) return null; String name = null; for (Field f : pojo.getDeclaredFields()) { Id id = null; Column column = null; Annotation[] as = f.getAnnotations(); for (Annotation a : as) { if (a.annotationType() == Id.class) id...

How to know the class type without using instanceOf or getClass()?

java,inheritance,reflection

Generally speaking, the third-party API in this case is badly designed. Especially if you are allowed to change the classes it relies on... But anyway, if you are allowed to change the classes, you can add a method like displayMe (I'm assuming your third party class is called PersonPrinter). abstract...

Reflection - GetProperties of a class that are Interfaces [duplicate]

c#,reflection

Use Type.IsInterface to determine if the type of a property is an interface type. Type t = typeof ( YourType ); foreach ( PropertyInfo p in t.GetProperties () ) { if ( p.PropertyType.IsInterface ) { // p is an interface property } } ...

Spring MVC send all model classes as json string

jquery,json,spring-mvc,reflection,toolbox

After quite a bit of googling and trying and failing, I have settled with the following fix. I have a Util class that gets me a json string if I pass it a Class. I'm now using Jackson Library to get json representation. public class Util { public static String...

Are repeated calls to Type.GetMethod() cached internally?

c#,.net,reflection

my problem is not so much a speedy invocation as it is making sure the Type.GetMethod() calls are not incurring big hits every time they are being called on the same methods Then you will need to cache the MethodInfo object for a given method name. The CLR does...

C# - Get all types that been used in class A

c#,reflection,types

[MyAttribute(new OtherType(TestEnum.EnumValue1))] That's not valid, you have to have a constant in attribute constructors. That matter aside, most of this is easy, if rather long-winded. You can call typeof(MyClass).CustomAttributes.Select(ca => ca.AttributeType) to get the types of attributes, typeof(MyClass).GetFields().Select(fi => fi.FieldType) to get the types of fields, and so on. Union...

Get private property of a private property using reflection

c#,reflection

You can use the GetProperty method along with the NonPublic and Instance binding flags. Assuming you have an instance of Foo, f: PropertyInfo prop = typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo getter = prop.GetGetMethod(nonPublic: true); object bar = getter.Invoke(f, null); Update: If you want to access the Str property, just do...

Generic Programming in Go, Implicit generic type

generics,reflection,go

convertedObject is the value of what is in the object interface. Taking the address of that has no effect on the original customer. (and converted is probably a poor prefix for the name, since that is generated from a "type assertion", not a "type conversion") If you use object directly,...

can we call a method having argument as java.lang.reflect.Array?

java,reflection

Array is just a helper class - note how all the methods on it are static. I wouldn't expect there to ever be an instance of it. To accept an array - and any array, including int[] etc - you'd need to make the method accept Object: public static void...

Idiomatic alternative to reflection

reflection,rust

Since all the algorithms implement the same trait Digest, which offers everything you need, you can box all the algorithms and convert them to a common Box<Digest>: let mut digest: Box<Digest> = match my_algorithm { "sha256" => Box::new(Sha256::new()), ... }; Now you don't know anymore what the type was, but...

How can I rewrite this LINQ query with reflection

c#,linq,dynamic,reflection

Use the reflection to create the query, not in the query. Consider: public static IQueryable<Profile> Filter( this IQueryable<Profile> source, string name, Guid uuid) { // .<name>UUID var property = typeof(Profile).GetProperty(name + "UUID"); // p var parExp = Expression.Parameter(typeof(Profile)); // p.<name>UUID var methodExp = Expression.Property(parExp, property); // uuid var constExp =...

Go reflect. How to check whether reflect.Type is an error type?

reflection,go,metaprogramming

In Go error is not something special. error is just a predeclared interface type so it doesn't have its own Kind in reflect. Try something along: errorInterface := reflect.TypeOf((*error)(nil)).Elem() ... case reflect.Interface: if typOute.Implements(errorInterface) // it's an error ...

Getting List type of class from ParameterizedTypeImpl

java,generics,reflection

I ended up with the following code ParameterizedType targetMapParameterizedType = (ParameterizedType) targetMethodMap.get(targetMethodName).getGenericParameterTypes()[0]; Class<?> mapType = targetMethodMap.get(targetMethodName).getParameterTypes()[0]; if(mapType.isInterface()) { newMap = new HashMap<Object, Object>(); } else { try { newMap = (Map<Object, Object>) mapType.newInstance(); } catch(Exception e) { newMap = new HashMap<Object, Object>(); } } Class<?> targetKeyType = null; Class<?> targetValueType...

Ruby - How to find class name given an instance variable?

ruby,reflection,introspection

You can't, you can get the class name of an instance variable, but the "instance variable of an instance" has its own class (it's still an object). So student.name.class will return String, student.class will return Student. If you want such a binding (student name => student class) you have to...

How to use reflection with Core Data and Swift

ios,swift,core-data,reflection

I believe that this code can help you. I wrote this extension to make a dictionary from a NSmanagedObject and it accesses all attributes and values of the object. extension NSManagedObject { func toDict() -> Dictionary<String, AnyObject>! { let attributes = self.entity.attributesByName.keys let relationships = self.entity.relationshipsByName.keys var dict: [String: AnyObject]...

Cost of reflection: WPF

c#,reflection

If you know the type at compile-time, you'd be a lot better off making this generic: // Possibly add more generic constraints to T? public static Window OpenUserControl<T>(string title) where T : new() { return new Window { Title = title, Content = new T(), ShowInTaskbar = false }; }...

Scala Reflection - MethodSymbol erasure warning unless importing universe._

scala,reflection

The reason is pretty simple. Universe has an implicit method named MethodSymbolTag (mixed in from the Symbols trait) defined like this: implicit val MethodSymbolTag: ClassTag[Universe.MethodSymbol] The presence of a ClassTag[Universe.MethodSymbol] in scope allows the compiler to curcimvent erasure. You can verify this by adding this import in your second code...

Advantage of using CustomAttributes vs GetCustomAttributes()

c#,.net,reflection,custom-attributes

You are making a traditional benchmarking mistake, one that makes many .NET programmers think that Reflection is slow. Slower than it actually is. Reflection is very lazy, you don't pay for it when you don't use it. Which makes your first measurement include all the cost of page-faulting the metadata...

Create generic Func from reflection

c#,reflection,delegates

You can solve this by building an expression tree manually, and inserting a cast to hiddenType. This is allowed when you construct an expression tree. var typeConst = Expression.Constant(hiddenType); MethodInfo getInst = ... // <<== Use reflection here to get GetInstance info var callGetInst = Expression.Call(getInst, typeConst); var cast =...

Instantiate type-parametrized class at runtime with default constructor

scala,reflection

The T: ClassTag syntax is called a context bound. It is syntactic sugar for an implicit parameter of type ClassTag[T]. In other words, the following class signatures are equivalent: class Test[T : ClassTag](val value : T) class Test[T](val value: T)(implicit val ev: ClassTag[T]) So the constructor you're looking for expects...

Insert/Inject an Object to string code

c#,reflection,system.reflection,codedom,csharpcodeprovider

You need to generate the code which creates this variable and fills it with the values you have. Or you can add an argument for one of the methods you generate and pass it at runtime. There's no magic method which will do it fo you. CodeDom is incomplete, obsolete...

Cast object to unknown type

c#,asp.net,reflection

You can use dynamic keyword, assuming you are running .NET 4 or above public void PopulateDropDownList(DropDownList ddl, IEnumerable list, Type type) { foreach (var item in list) ddl.Items.Add(new ListItem(((dynamic)item).Name, ((dynamic)item).ID.ToString())); } Or, (if) you can use generic version and pass accessors to get the key and value. public void PopulateDropDownList<T>(DropDownList...

Listing Scala nested objects methods through Reflection

scala,reflection

When you use typeOf[m.type] in the foreach, you are getting the type of the instance of m, which is of type Symbol, so that isn't what you want. You can use the info method on Symbol to get the Type instance you are looking for: typeOf[BusinessFacade.type].members.filter(_.isModule).foreach { m => println(m.name...

Get actual class from stack trace element

java,debugging,reflection,stack-trace

The stack records which code is waiting for a call to return, not which objects. If the method is in the superclass and the subclass doesn't override it, the stack will record the superclass method, because that's where control must eventually return to. The only way to get at the...

What is System.Reflection.Module?

.net,reflection,bcl

An assembly can consist of multiple modules and even be split up into multiple files. There are two primary use cases for using modules: Combining modules written in different languages / compiled by different compilers in one assembly Optimize downloading speed of an application by having a lightweight main module...

Generic method for retriving a single object c#

c#,generics,reflection

Just call var employee = table.DataTableToList<Employee>().FirstOrDefault(); Alternatively (if your DataTable is very large), you might want to modify your extension method to return an IEnumerable<T> instead, using the yield keyword: public static IEnumerable<T> DataTableToList<T>(this DataTable table) where T : class, new() { try { foreach (var row in table.AsEnumerable()) {...

Correct Parameter Type for GetMethod

c#,reflection

I believe the answer to your question is, "There is no way to do this". Since GetMethod is not able to "MakeGenericMethod" while its doing its lookup, you have a method with one generic parameter that's known (TClass) and one that's not (TMethod). Reflection can't look up a method when...

Pattern Matching chooses the wrong case if used with ClassTag

scala,reflection,covariance

I definitely think it is a compiler bug. def test1[T:ClassTag](v:In[T]) = { val t1 = classTag[T] == classTag[T1] val t2 = classTag[T] == classTag[T2] println(v match { case x : VIn[[email protected]] if t1 => "T1" case y : VIn[[email protected]] if t2 => "T2" }) v match { case x:In[T1] if...

Construct the name of the method to be called at runtime

java,design-patterns,reflection

You could do that by reflection, but for this case is clearly overkill. What about this approach?: Store your objects in an array (or a List) and then use the index to access the required one. Note that I'm assuming that all the objects are of the same class or...

How can I resolve the Class type for generic parameter, when the parameter value is being passed as an interface?

c#,.net,generics,reflection

If you want to get a flat list of all object properties contained inside the List<T>, here's a LINQ solution: IEnumerable<PropertyInfo> properties = myList.SelectMany(x => x.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance)); If you need to access the declaring type, you can always look PropertyInfo.DeclaryingType If you don't want a flat list, Select...

How do you use reflection to get a sub property?

c#,.net,reflection

Get hold of the current value of Person, then update it in the same way as you currently are: PropertyInfo subPropertyInfo = apptObject.GetType().GetProperty("Person"); Object p = subPropertyInfo.GetValue(apptObject); PropertyInfo subSubPropertyInfo = p.GetType().GetProperty("Name"); subSubPropertyInfo.SetValue(p, replacementValue, null); ...

How I can access instance from MethodInfo

c#,.net,reflection

The reflection data in the MethodInfo class are associated with the method in general, not with any particular instance. Thus, you can't get the information you're looking for from that class. Instead, the Delegate.Target property will return the instance associated with the received delegate (which I'm assuming is what you're...

Correctly distinguish between bool? and bool in C#

c#,reflection

Code for getting class instance values: // create class instance InstViewModel model = new InstViewModel() { Uk = true, UkNrs = false, }; // check all boolean fields are false or null bool isAllNullOrFalse = (from property in typeof(InstViewModel).GetProperties() let type = property.PropertyType let isBool = type == typeof(bool) where...

Is it bad to have an empty attribute class?

c#,reflection,attributes

No. Attributes are frequently used just as flags. Take the pervasive: [Serializable] If you reflect into its source code, it's basically blank inside (it just has some constructors), but it's one of the most used attributes in .NET. The same thing goes for attributes like [XmlIgnore]....

What's the difference or relationship between Type and TypeInfo?

.net,reflection,types

From the MSDN docs: A TypeInfo object represents the type definition itself, whereas a Type object represents a reference to the type definition. Getting a TypeInfo object forces the assembly that contains that type to load. In comparison, you can manipulate Type objects without necessarily requiring the runtime to load...

PHP Reflection: How to know if a method/property/constant is inherited from trait?

php,inheritance,reflection,traits,trait

Important notes This is only because of "academical" interest, in real situation you should not care about - from where method was derived as it contradicts the idea of traits, e.g. transparent substitution. Also, because of how traits are working, any kind of such manipulations might be considered as "hacky",...

Python: Creating a new instance of itself from a base class (possibly via reflection?)

python,reflection,constructor

You can use the __class__ attribute of the value: class A(object): pass class B(A): pass b = B() c = b.__class__() ...

Create new object knowing reflected type

reflection,go

To tell what you're doing wrong we should see more of your code. But this is a simple example how to do what you want: type Person struct { Name string Age int } func main() { p := Person{} p2 := create(reflect.TypeOf(p)) p3 := p2.(*Person) p3.Name = "Bob" p3.Age...

Yii2: How to add validation rules to the model class dynamically?

php,reflection,model,yii2

You can code the rules()-function to build an array of validation rules depending on the scenario and data input. It is not a requirement that this is a fixed array. Unfortunately doing it this way will leave you with validation issues on the frontend (should you need that), dynamic rules...

How can I specify the type of the field that an Annotation should be applied to in Java?

java,android,reflection,annotations

Yes, you can cause the compiler to issue an error message if you write the annotation on a field of the wrong type. You cannot do this using just the @Target meta-annotation. Instead, you need to write an annotation processor. The annotation processor will examine each occurrence of the annotation...

Get object by attribute value [duplicate]

c#,reflection,custom-attributes,spring.net

If you have obtained the Assembly, you can just iterate over the types and check for your conditions: var matchingTypes = from t in asm.GetTypes() where !t.IsInterface && !t.IsAbstract where typeof(ICustomInterface).IsAssignableFrom(t) let foo = t.GetCustomAttribute<FooAttribute>() where foo != null && foo.Bar == Y select t; I am assuming you want...

Can't obtain parameterless constructor of a struct [duplicate]

c#,reflection,struct

You don't need to invoke the parameterless constructor of a struct. Just use the activator for creation: Activator.CreateInstance(i.GetType()); The reason you can't obtain a parameterless constructor of a struct is that it just does not exist....

Generic Programming in Go. Avoiding hard coded type assertion

reflection,go,generic-programming

Finally i find a way to do that. Follow the Go Playground and code snippet below: GO Playground: Avoiding Hard Coded Type Assertion //new approach SetAttribute, without any hard coded type assertion, just based on objectType parameter func SetAttribute(myUnknownTypeValue *interface{}, attributeName string, attValue interface{}, objectType reflect.Type) { // create value...

Instantiate generic c# List when the reflected type itself is a List

c#,asp.net,list,generics,reflection

Have a look at this example, it uses the Type.GetGenericArguments Method to retrieve the lists inner type. Then proceed with reflection as usual. static void Main(string[] args) { Type modelType = GetMyType(); var myList = Activator.CreateInstance(modelType); var listInnerType = modelType.GetGenericArguments()[0]; var listInnerTypeObject = Activator.CreateInstance(listInnerType); var addMethod = modelType.GetMethod("Add"); addMethod.Invoke(myList, new[]...

Dynamically access methods from scala object

scala,dynamic,reflection

You could still use scala runtime reflection: import scala.reflect.runtime.{universe => ru} val m = ru.runtimeMirror(getClass.getClassLoader) val ccr = m.staticModule("my.package.name.ObjName") // e.g. "CC" or "CD" type GetC = { def getC(name:String): CC } val cco = m.reflectModule(ccr).instance.asInstanceOf[GetC] now you could use it as cco.getC ......

ClassCastException while trying to get the generic type parameter

java,generics,reflection

Do not know where is problem, maybe someaone can help me The error message is self explanatory. The following statement returns a Class : (getClass().getGenericSuperclass()) And you are trying to cast it to a ParameterizedType ((ParameterizedType) (getClass().getGenericSuperclass())) Class and ParameterizedType are siblings. A brother is not a sister so...

Create general method to fit interface and general parent class

java,generics,reflection

You can use generics to say that you expect an object that has both characteristics private <T extends Shape & Fillable> void setFilledAndAdd(T obj, Color color, int x, int y){ obj.setFilled(true); // needs interface Fillable obj.setFillColor(color); add(obj, x, y); } private void add(Shape s, int x, int y){ // whatever...

Is it justified to use Reflection in this use case to workaround design issue that i am not allowed to fix?

java,xml,inheritance,reflection,xml-binding

I'd try an alternate solution for generating your classes from the xml schema, in preference over reflection. You can supply xjc with a custom binding like this: <?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://java.sun.com/xml/ns/jaxb" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd" version="2.1"> <globalBindings> <xjc:superClass...

How to get value of unknown properties (part solved already with reflection)

c#,reflection,properties

this is how you can do it. (by the way, your code might error out on "dictionary key not being unique" since the second userItem will try to add the same property name to the dictionary. you might need a List<KeyValuePair<string, string>>) foreach (var property in theProperties) { // gets...

How to get parameter names via reflection in kotlin?

reflection,kotlin

The current solution is to use the JetValueParameter annotation, although it is deprecated. We're working on support for the parameter names in Kotlin reflection, which will be available shortly. At that point JetValueParameter will be dropped in favor of the new API. I'd like to note that Kotlin compiler currently...

Instantiate a class which implements a generic interface

c#,reflection

You're mixing up the factory and the entity. That's unnecessary - it really doesn't make sense to have GetData be an instance method on BTAC. Activator.CreateInstance returns object - you need to explicitly cast it to the type you want. Neither of your types implements ILabelData<object>. The thing is,...

Convert List to typeof UnderlyingSystemType

c#,list,inheritance,reflection,dynamic-linq

depending on the actual use cases, some things can be improved: runtime expenses: the CreateListOfCorrectType function copies all elements into a new collection which results in unnecessary expense in case only a subset is taken out of the returned collection . scope of applicability of the mapping function: this could...

Java prevent calling private or protected methods outside of class

java,reflection,private

You need a security manager... https://docs.oracle.com/javase/tutorial/essential/environment/security.html A security manager is an object that defines a security policy for an application. This policy specifies actions that are unsafe or sensitive. Any actions not allowed by the security policy cause a SecurityException to be thrown. An application can also query its security...

Creating an instance from assembly throws a memory leak

.net,reflection,memory-leaks

After 2 days searching on the net i have been able to resolve the error. This is the solution for anyone on my situation. The classes you want to load by reflection have to implement the IDisposable interface. These classes have to override the Dispose method. In this method, simply...

Is it safe to use OpCodes.Call on a virtual method?

c#,.net,reflection,reflection.emit

You don't usually want the implementation from the declaring type. Presumably you want to do the same thing that the base keyword would do with the C# compiler. The C# compiler actually looks up the most-derived parent implementation and directly calls it, but what you are doing is also perfectly...

Make Func<> for a generic type

c#,reflection

From what I get from the comment, is that you want to access getters through a string key? If that is the case, you might want to use the code sample below. The entity you want to access: class Entity { public int Foo { get { return 42; }...

Identify test classes dynamically

java,reflection,junit,testng

Below are some steps you can follow : Get Jar file path Read classes from it Iterate through those classes Get methods of each class Check for annotations used in each class. Latest versions of JUnit test classes have @Test annotation. So if you get @org.junit.Test annotation, you can say...

Java Reflections 'NoClassDef' error

java,reflection,runtime-error

java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile You can fix the issue by adding javassist-3.12.1.GA.jar to your classpath ...

How do I access parameters specified in a Java Aspect?

java,reflection,annotations,aop

The trick is to query the aspect's JoinPoint object to get annotation information about the method (or class or whatever) that's annotated. That's the glue I couldn't figure out. Here's an example. First, the interface of the aspect. This annotation will only be applied to methods. @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface...

How should I be using LambdaMetaFactory in my use case?

java,reflection,lambda,java-8

If you looked at your log output you noticed that your target method signature looks like (Lme/b3nw/dev/Events/Vanilla;Lme/b3nw/dev/Events/GameEvent;)Z, in other words, since your target method is an instance method, it needs an instance of its class (i.e. Vanilla) as first argument. If you don’t provide an instance at lambda creation time...

Convert json to struct using reflection in golang

json,reflection,go

The problem is that you are passing a non pointer instance of the type: payload:=reflect.New(v).Elem().Interface() Means "allocate a new pointer to the type, then take the value of it, and extract it as interface{}. You should just keep it at: payload:=reflect.New(v).Interface() BTW It's also redundant that you are passing the...

How to loop through the properties of a Class? [duplicate]

c#,class,reflection,properties

Something like: object obj = new object(); PropertyInfo[] properties = obj.GetType().GetProperties(); foreach (var p in properties) { var myVal = p.GetValue(obj); } Note you need to allocate the object and pass it into the PropertyInfo. ...

java compilation error when using reflection with templates

java,templates,reflection,compiler-errors

Just cast private <D extends Object> void foo(D d) throws IllegalAccessException, InstantiationException { d = d.getClass().cast(d.getClass().newInstance()); // Compilation error: "Incompatible types: Required D, Found: Object" } ...

Get the public properties of a class without creating an instance of it?

javascript,reflection,typescript

Do you know if it is possible to get the public properties of a class without creating an instance of it? If you are talking about runtime them no, not without ugly hacks like toString (which gives you a string representation of the function body). However you can get...

Extension methods with base and sub-classes

c#,inheritance,reflection,extension-methods

Creating the two extension methods for Parent and ChildA, you can move the association to runtime by using dynamic. Console.WriteLine(string.Join(", ", commands.Select(c => Extensions.Run(c as dynamic)))); ...

How to get the foregrund activity instance?

android,android-activity,reflection

Without knowing why you want an instance of the Activity, or other background info. I'd suggest the following. If you're inside a Fragment, then you can do getActivity() - which will give a reference to the Activity, and you can then cast this as your own Activity. Otherwise, you might...

Get the method name that was passed through a lambda expression?

.net,vb.net,reflection,delegates,pinvoke

I would not do this. It would be simpler to pass a string var representing the error message you want to display or a portion thereof (like the function name). The "simplest" way would be to use an Expression Tree. For this, you would need to change the signature of...

Get a retrun value from dynamically calling java class [duplicate]

java,reflection,dynamic-method

in Method.invoke(...) you should not pass the parameter types, but the actual parameter values. Please check the java documentation for Method.invoke(...).

Bound mismatch mitigation

java,generics,reflection

public class Main { public <T> SomeInterface<T> getImplementation(Class<T> clazz) { if(SpecificClass.class.isAssignableFrom(clazz)) { // do some specific stuff // unchecked cast here... return (SomeInterface<T>) getSpecificImplementation((Class<SpecificClass>) clazz); } else { // do other stuff return new CatchAllImplementation<T>(); } } private <T extends SpecificClass> SomeInterface<T> getSpecificImplementation(Class<T> clazz) { return new SpecificImplementation<T>(); } public...

Deserializing Generic Types from a ClassLouder class with GSON

java,json,generics,reflection,gson

see here a default implementation of ParametrizedType: http://www.java2s.com/Code/Java/Generics/DefaultimplementationoflinkjavalangreflectParameterizedType.htm properly prepared, such a type could be used to represent a generic type, which may work with GSON. Without having tested it, your code might then look like this: File root = new File("./build/classes"); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });...

Java Reflection vs Java Debug Interface (JDI) [closed]

java,debugging,reflection,jdi

From the JDI documentation The JavaTM Debug Interface (JDI) is a high level Java API providing information useful for debuggers and similiar systems needing access to the running state of a (usually remote) virtual machine. The JDI provides introspective access to a running virtual machine's state, Class, Array, Interface, and...

Using reflection to get attribute names in struct returns value__

c#,reflection,struct,attributes

you should use :var t = typeof(ItemTypes).GetFields().Where(k => k.IsLiteral == true);

How to refactor repeated code using reflection

c#,linq,generics,azure,reflection

Answering on original question how to rewrite this in generic way with reflection, so that method should not require changes for every new social network. If MySpace gonna be handled, you need just to add it to handlerMapping, HandleAnySocialNetworkByMapping() not changing (see code below). class Program { private readonly static...

Reflection doesn't recognize that class is inherited C#

c#,inheritance,reflection,attributes

Just change this line: foreach (var a in Attribute.GetCustomAttributes(typeof(cl1))) to foreach (var a in Attribute.GetCustomAttributes(this.GetType()))...

Can Java class files use reserved keywords as names?

java,reflection,jvm,.class-file

The only restrictions on class names at the bytecode level are that they can't contain the characters [, . or ; and that they're at most 65535 bytes long. Among other things, this means that you can freely use reserved words, whitespace, special characters, Unicode, or even weird stuff like...

Static var in protocol and reflection

ios,swift,reflection

Personally, I'd use overloading in this situation: func nameForClass<T>(Type: T.Type) -> String { return "\(Type)" } func nameForClass<T: Nameable>(Type: T.Type) -> String { return Type.name.isEmpty ? "\(Type)" : Type.name } Usage: println(nameForClass(A.self)) // Prints "ClassA" println(nameForClass(B.self)) // Prints "__lldb_expr_47.B" An advantage of not using AnyClass is that you can also...

Java Reflection, extract generic type from method

java,generics,reflection

It's not possible. Generics in Java are "syntactic sugar". They are only used at compile-time but are then removed and never make it into the class file. This question has some realy good information on this....

How to determine dynamically if type is an Interface using reflection?

c#,reflection,interface

You can use Type.IsInterface Property https://msdn.microsoft.com/en-us/library/system.type.isinterface(v=vs.110).aspx

InvalidCastException when casting dynamically to interface

c#,reflection,f#

It turns out that I actually had to unbox the object instead of casting it, and then it worked just fine. let hwIns = asm.CreateInstance("HelloWorld") |> unbox<IHelloWorld>...

Trying to detect a circular reference in Java with reflection

java,reflection,circular-reference

Figured this out myself in the end. Part of the confusion I encountered using the Reflection API is that, for example, when you invoke Field.get(object); object has to be an instance of the class that contains the field, which makes sense but is not immediately intuitive (it wasn't to me...

Reflection , java , iterate on collection

java,reflection,collections

Have you tried something like: void printFieldsOfClass(Object obj) { if (obj == null) { return; } // Deal with collections... if (obj instanceof Collection) { for (Object o : ((Collection<Object>) obj)) { printFieldsOfClass(o); } return; } // Otherwise it is a 'simple' object... Class<?> mainClass = obj.getClass(); // create instance...

Go reflect.MakeFunc. How to return a err=nil as reflect.Value?

reflection,go,generic-programming

It's tricky, you have to use reflect.Zero: out[2] = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem()) play...

Plugin-system: How to handle events between host application and plugin

c#,.net,events,plugins,reflection

I would advise you to rethink the architecture of your application to use standard solutions to your problem. As Aron points, you can make use of an EventAggregator to publish and subscribe to events within your whole application. You can make use of any of the many implementations that are...

Create list of runtime-known type from object list and call generic method

c#,linq,dynamic,reflection

Quite easy: public static class DynamicLinqExtensions { public static IEnumerable<TSource> FilterByUniqueProp<TSource> (this IEnumerable<TSource> query, TSource model) { // Do something accourding to this type var type = typeof(TSource); return null; } public static IEnumerable<TSource> FilterByUniqueProp2<TSource> (this IEnumerable<object> query, TSource model) { // We use Cast<>() to conver the IEnumerable<> return...

How to speed up the class scan via Reflection API in Java?

java,reflection

Use FilterBuilder to exclude java root package at least. And it may help to specify SubTypesScanner as that's what you're doing. Reflections ref = new Reflections(new SubTypesScanner(), new FilterBuilder().excludePackage("java")); ...

JavaClassLoader: Why an “NoSuchMethodEx” is thrown here?

java,reflection,nosuchmethoderror,cglib

jcl: manipulating-class-loading-order @ChristianFrommeyer gave me the solution. I want to explain it, so it's own answer. The launcher is still loaded by the "normal" class loader. All objects that are loaded in this class will be loaded by the same class loader as the Launcher. I load now from the...

Getting inherited public static field with Reflection in Portable Class Libraries

c#,.net,reflection,portable-class-library

You could use: public static FieldInfo[] DeclaredFields(TypeInfo type) { var fields = new List<FieldInfo>(); while (type != null) { fields.AddRange(type.DeclaredFields); Type type2 = type.BaseType; type = type2 != null ? type2.GetTypeInfo() : null; } return fields.ToArray(); } ...

Obtain non-explicit field offset

c#,.net,reflection,clr

With some tricks around TypedReference.MakeTypedReference, it is possible to obtain the reference to the field, and to the start of the object's data, then just subtract. The method can be found in SharpUtils.

Reflection on IQueryable OfType<>

c#,entity-framework,generics,reflection

Try var obj = methodinfo.Invoke(null, new[] { employees }); The OfType is static, so null obj (the first parameter of Invoke, that is the instance of the object to use for the method)!...

Why BindingFlags are called so?

c#,wpf,reflection

Because the class that translates the metadata to a actual method is called Binder and BindingFlags are flags that are passed on to the binder to connect to the method.

Missing something in this method to get the Entity property

c#,asp.net-mvc,reflection,entity

var result = new List<string>(); var type = eContentField.GetType(); foreach (var prop in type.GetProperties()) { result.Add(prop.Name); } return result.ToArray(); } This is about twice faster than your method, if you are interested in speed. Ps: if you change the foreach into a for loop, it wil be a bit faster,...

Need to print function's actual parameter name used while calling

java,performance,swing,reflection

Unless the values of a, b and c never changes (and you can deduce which variable was used as argument by looking at the value) this is not possible. You need to pass more information to the method. One way would be to do public void click(int x, String identifier)...

Java Reflection. Access the value of a field

java,reflection,illegalargumentexception

In this line... System.out.println((String)fx[j].get(c)); The variable c is of type Class and not of type Book. You need to pass get() an instance of Book....