FAQ Database Discussion Community


Identify test classes dynamically

java,reflection,junit,testng
I required a solution to identify test classes from a jar file and execute them .That is my web application accept a jar file as input and identify test classes inside the jar and execute them and show the result. Currently I am facing class not found exception whenever I...

InvalidCastException when casting dynamically to interface

c#,reflection,f#
I have an interface defined in an assembly like this: namespace HelloWorlder { public interface IHelloWorld { string SayHello(); } } In a seperate assembly I have another class defined as: using HelloWorlder; public class HelloWorld : IHelloWorld { string IHelloWorld.SayHello() { return "Hello, world!"; } } Now trying to...

Convert List to typeof UnderlyingSystemType

c#,list,inheritance,reflection,dynamic-linq
I am currently working on code that is using dynamic-linq, I ran into a problem when using a List<BaseClass>, where the list actually contains a list of the Person Class. When I execute the following code I get a ParseException: var list = new List<BaseClass>(); list.Add(new Person { FirstName =...

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

java,reflection
I use org.reflections library to scan ClassPath and get classes. Here is my code: Reflections ref = new Reflections(); Set<Class<? extends Service>> classes = new HashSet<>(); for (Class<? extends Service> subType : ref.getSubTypesOf(Service.class)) { if (!Modifier.isAbstract(subType.getModifiers())) { classes.add(subType); } } But I faced a problem. It takes too much time....

Using reflection to get attribute names in struct returns value__

c#,reflection,struct,attributes
I want to populate a combo box with all of the available item types in my struct ItemTypes: public enum ItemTypes { Ore, Ice, Mineral, Pi } In order not to add a new item type in 2 places if I do have to add one eventually (not likely, but...

How do I access parameters specified in a Java Aspect?

java,reflection,annotations,aop
I have an annotation called "@ProgressCheck" that we can put on a controller to check the progress of an application. If the application is already submitted or late, then it throws the user to a page appropriate for that situation. The annotation interface is: @Retention(RetentionPolicy.RUNTIME) public @interface ProgressCheck { }...

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

c#,asp.net,list,generics,reflection
I have a reflected Type, which ends up being a List<Type>. So I have: Type modelType = GetMyType(); So - modelType could be List<ClassA> or List<ClassB>, etc. depending on the situation. How do I create this type, and then populate it? I know I can do this: var myList =...

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

java,debugging,reflection,jdi
What are the differences between use Java Reflection and Java Debug Interface? when can I use one and when the other?

Generic method for retriving a single object c#

c#,generics,reflection
I've been looking at this method for a while now and trying to figure out how it works. This clearly works for returning a list of objects just perfect. But what I can't currently figure out is how I would retrive a single object for instance "Employee e" and not...

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

c#,reflection,interface
For starters, this question is not a repeat of this post that I have read 100 times (please read on for question): How to determine if a type implements an interface with C# reflection I'm using reflection to iterate through properties on objects dynamically at runtime to manipulate and add...

Reflection , java , iterate on collection

java,reflection,collections
I'm writing a function that will iterate on some collection , I don't know what collection I'm getting , so I wrote this till now , the PrintFieldsOfClass will get some object or collection of objects and I will have to print the fields of the class , I have...

Create general method to fit interface and general parent class

java,generics,reflection
I have the following method: private void setFilledAndAdd(Shape obj, Color col, int x, int y) { obj.setFilled(true); // needs interface Fillable obj.setFillColor(col); add(obj, x, y); // needs children of Shape (or Shape itself) } If I add one of the lines: setFilledAndAdd(oval, color, x, y); Compile time error apears in...

Getting inherited public static field with Reflection in Portable Class Libraries

c#,.net,reflection,portable-class-library
Within a Portable Class Library, I have 2 classes: The parent public class Parent { public string inherited; public static string inheritedStatic; } And the child the derives from it public class Child : Parent { public static string mine; } The problem is that I cannot get the inherited...

How should I be using LambdaMetaFactory in my use case?

java,reflection,lambda,java-8
Despite having read all the documentation I'm aware of, I cannot resolve an issue with using lambdas to execute a method. To give a bit of background my use case is a plugin system. I'm using an annotation (@EventHandle) which can be assigned to any method. I use reflection and...

Java Reflection. Access the value of a field

java,reflection,illegalargumentexception
I am trying to complete a program with Java Reflection. I have a problem with this part. I can not get the value of the field I am looking for. Field [] fx = ArrayUtils.addAll(c.getDeclaredFields(),c.getFields()); for (int j = 0; i < fx.length; j++){ System.out.println(fx[j].toString()); if( fx[j].isAnnotationPresent(Searchable.class)){ Searchable ann =...

Check if this pointer was accessed in an instance method

c#,.net,reflection
I am trying to detect if the this pointer was accessed in a dot net instance method. Could be a call to an instance method, access to a member variable etc. Currently digging into Reflection: MethodBase.GetMethodBody if I can figure it out from the IL. ...

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

java,reflection,dynamic-method
This question already has an answer here: How do I invoke a Java method when given the method name as a string? 11 answers I need to get a retrun value from dynamically calling java class by passing a variable values to that calling method. I try to use...

Java Reflections 'NoClassDef' error

java,reflection,runtime-error
I'm trying to browse all classes that have implemented an interface using the custom libary Reflections. Here is my source : public static List<IModdable> getAllModClasses() { Reflections reflections = new Reflections("mod.api.core"); //getting error here Set<Class<? extends IModdable>> classes = reflections.getSubTypesOf(IModdable.class); List<IModdable> modList = new ArrayList<IModdable>(); for (Class<? extends IModdable> c...

Getting List type of class from ParameterizedTypeImpl

java,generics,reflection
I have a field of Map I am trying instantiate that looks like this Map<Long, List<MyObj>> The code to convert it is this 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(); }...

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

ruby,reflection,introspection
How can I find a class name given its instance variables? For example, given the class below: class Student attr_accessor :name end and, the object below: student = Student.new student.name = "John Doe" How can I get the class name (or its Class object) from the instance variable name of...

JavaClassLoader: Why an “NoSuchMethodEx” is thrown here?

java,reflection,nosuchmethoderror,cglib
I have a problem with the "JavaClassLoader" library. I want to program a launcher for a application. At the end it should be possible to shutdown the program, to update and to start again. Now, I always get an NoSuchMethodEx when I try to invoke methods with arguments. The main...

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

c#,reflection,types
how can I get all the types that been used in specific type? Example for class "MyClass": [MyAttribute(new OtherType(TestEnum.EnumValue1))] public class MyClass:MyOtherClass { public Type MyType { get; set; } public string MyString { get; set; } private DateTime MyDateTime; [OtherAttribute()] public int MyMethod(double doubleNumber, float floatNumber) { justMyClass myJustClass...

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

.net,vb.net,reflection,delegates,pinvoke
Is it possible to retrieve via Reflection the real method name that was passed through a lambda expression? I would like to platform invoke some functions with a better error-handling, then to avoid repeating tons of Marshal.GetLastWin32Error conditionals, I thinked in create a generic method to automate that, where I...

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

c#,reflection,properties
I have an existing c# application to modify and need to loop through an object with unknown properties and have half solved the problem with reflection. I'm trying to populate a dictionary with the property name and the property value. The code is below and I've given a description of...

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
Would the following use case be considered as justified for Reflection? There are bunch of classes generated from XSDs (hundreds currently on project) which represent various Responses. All of these Responses include common response data structure, rather then extending it. When event such as timeout happens, i only need to...

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

java,performance,swing,reflection
I want to print function actual parameter name in function. For reference please refer below code.Here i am trying reflection. class Refrction { public static int a=12; public static int b=12; public static int c=13; public void click(int x) { Class cls=Refrction.class; Field[] fields = cls.getFields(); //here i want to...

Trying to detect a circular reference in Java with reflection

java,reflection,circular-reference
I've inherited some legacy code that fails if there's a circular reference. The code takes an object and builds the entire graph of objects for conversion to XML. The legacy code can't be modified, so I want to detect the reference and handle it accordingly. For now, I'm building up...

How do you use reflection to get a sub property?

c#,.net,reflection
Let's see if I can explain what I'm trying to do... Say I have an object, with a path to a property that looks like this: Appointment.Person.Name If I want to update the "Person" property, i could do something like this: PropertyInfo subPropertyInfo = apptObject.GetType().GetProperty("Person"); subPropertyInfo.SetValue(apptObject, replacementValue, null); But how...

How to get the foregrund activity instance?

android,android-activity,reflection
I try to get the foreground activity for a long time, and i didn't managed to get it until now. I don't know if it even possible, but i am dont intersted in my app activity only. There is no data transfer between my service and the activity which i...

Correct Parameter Type for GetMethod

c#,reflection
In the code below, how should I be setting the variable "paramType" so that it matches the method shown in the GetMethod() call? The code below does NOT match the method in the sample class (methodInfo is null). using System; using System.Linq.Expressions; public class MyClass<TClass> { public void MyMethod<TMethod>( Expression<Func<TClass,...

Reflection on IQueryable OfType<>

c#,entity-framework,generics,reflection
I have a Employees DbSet in my Entity Framework context that can be queried as: IQueryable employees = _context.Employees; The Idea is to execute the below method using Reflection: var result= _context.Employees.OfType<PaidEmployee>() I have extended the Employee object to create an PaidEmployee class. I want to query the context for...

Missing something in this method to get the Entity property

c#,asp.net-mvc,reflection,entity
private String[] GetProperties(EContent_EcontentFields eContentField) { List<String> list = new List<String>(); Type fieldType = eContentField.GetType(); var properties = fieldType.GetProperties(); foreach (var prop in properties) { if (prop.MemberType == MemberTypes.Property) { if (prop.PropertyType.IsGenericType) { dynamic items = prop.GetValue(eContentField, null); foreach (var item in items) { Type typeItem = item.GetType(); list.Add(item); } }...

Extension methods with base and sub-classes

c#,inheritance,reflection,extension-methods
UPDATE Requesting to re-open because the other SO answers don't have a solution, but one of the comments to the question has a solution I want to accept as it works for the scenario. Original Question I am having trouble writing extension methods with non-abstract base classes and sub-classes that...

instance with Activator not access the properties , reflection

c#,reflection,activator,edmx-designer
I have a problem, I would like to make a generic method that instantiates the table of the model car, obviously by string. I applied this code: object item = Activator.CreateInstance(Type.GetType("eStartService." + tableName)); when I item.*something*, I do not see the properties of the table that should be called. It...

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

.net,reflection,types
I cannot fully understand when to use one or another. They are so similar that it's confusing me every now and them. When it comes to reflection, I don't know whether to use the plain Type or TypeInfo. .NET Framework itself adds more confusion with things like assembly.DefinedTypes. It retrieves...

How can I rewrite this LINQ query with reflection

c#,linq,dynamic,reflection
So I had written this LINQ query using reflection, and later found out it isn't supported. What would be the best way to get the same functionality from this code? List<Profile> profilesFromUUID = await MobileService.GetTable<Profile>().Where(p => typeof(Profile) .GetProperty(handler.Name + "UUID").GetValue(p) == obj.uuid).ToListAsync(); ...

Make Func<> for a generic type

c#,reflection
I have this architecture. public void Init() { PropertyInfo[] infos = typeof(Transform).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo info in infos) { // Save getter MethodInfo method = info.GetGetMethod(); System.Type returnType = method.ReturnType; System.Func<Transform, Vector3> fact = GetFactory<Transform, Vector3>(method); Vector3 v = fact(this.Value); Debug.Log("Test123 " + v); //_getters.Add(info.Name, newMethod); } } static...

Java prevent calling private or protected methods outside of class

java,reflection,private
Let's supppose that I have created a Java library, called Foo and I have a class inside that library called Bar. Let's suppose further that in the Bar class I have a private method, called fooBar. public class Bar { //... private Object fooBar() { //Do something } //... }...

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

java,reflection
I am having doubt on below code which uses parameter as java.lang.reflect.Array. public static void display(java.lang.reflect.Array stringArray) { System.out.println(java.lang.reflect.Array.get(stringArray, 1)); } Above mentioned code will compile successfully but whether i should write this method and what could be the possible use-case? if i can write such method how can we...

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

c#,.net,reflection,reflection.emit
I'm playing with generating dynamic proxies for properties. A generated proxy is derived from a type that we want to proxy. When the proxy needs to access a (virtual) property on the type it's derived from, OpCodes.Callvirt can't be used - it leads to infinite recursion. Thus we need to...

Correctly distinguish between bool? and bool in C#

c#,reflection
I am trying to find out if a variable is either a simple bool or a Nullable<bool>. It seems that if(val is Nullable<bool>) returns true for both bool and Nullable<bool> variables and if(val is bool) also returns true for both bool and Nullable<bool>. Basically, I am interesting in finding out...

Insert/Inject an Object to string code

c#,reflection,system.reflection,codedom,csharpcodeprovider
I have a C# code generated dynamically using System.CodeDom.CodeCompileUnit in runtime, I compile it using Microsoft.CSharp.CSharpCodeProvider , What I want is to insert an already defined & initialized Variable (an ArrayList) to this string so I could use it before compile, How should I do this?

Construct the name of the method to be called at runtime

java,design-patterns,reflection
I'm learning Java and I'm fairly new to this. Here is my problem with some pseudocode: public void objectCaller(int objectNumber) { switch(objectnumber) { case 1: object1.setFill(color.RED); break: case 2: object2.setFill(color.RED); break; . .and so on } } Is there a way to replace it in a way with something like...

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

php,reflection,model,yii2
As per the Yii2 docs validation rules can be applied either to the implicit properties (table fields) or to the userDefined properties. Is there a way to create validation rules for the properties which are dynamically added to the model class ? For example: Let there be model class named...

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

java,android,reflection,annotations
I'm creating a simple annotation, to help me inflating settings inside my Android application. The annotation is this: @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface CoreSettings { String name() default ""; } I want to ensure it will only be used in fields which type extends a custom class named BaseSettings. In the...

Spring MVC send all model classes as json string

jquery,json,spring-mvc,reflection,toolbox
I'm a noob to Spring MVC and JSON. I have a class hierarchy (interface, classes, subclasses) that I want to send across to my view and then resurrect the objects in the view (perhaps some Json library, currently using FlexJson). The idea behind this is I'm trying to generate a...

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

c#,linq,dynamic,reflection
I have IEnumerable<object> in memory. Let's say this: IEnumerable<object>() addedEntities = // ... some Linq-To-Object query Also, I have a method with this signature: public static IEnumerable<TSource> FilterByUniqueProp<TSource> (this IEnumerable<TSource> query, TSource model) { // Do something according to this type var type = model.GetType(); } As you see, this...

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

java,inheritance,reflection
I have a class Person which is inherited by Student and Employee. I have another class PersonList, it has a list of type Person i.e List (elements can be of both Student and Employee type) There is a 3rd party API which has two overloaded methods i.e void display(Employee emp)...

Convert json to struct using reflection in golang

json,reflection,go
func deserialize(request *http.Request,typ reflect.Type) (interface{}, *httpNet.HandlerError){ data,e:=ioutil.ReadAll(request.Body) fmt.Println(string(data)) if e !=nil{ return nil,&httpNet.HandlerError{e,"could not read request",http.StatusBadRequest} } v:=typ.Elem() payload:=reflect.New(v).Elem().Interface() eaa:= json.NewDecoder(request.Body).Decode(payload) if e!=nil{ fmt.Println(eaa.Error()) } fmt.Println(payload) fmt.Println(reflect.ValueOf(payload) ) return payload,nil } to call it: r,_:=...

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

c#,class,reflection,properties
This question already has an answer here: How do I automatically display all properties of a class and their values in a string? 5 answers I have found that this question is quite common, but i didn't found what i am looking for. Maybe 'cause i want to do...

Idiomatic alternative to reflection

reflection,rust
I am trying to select a digest algorithm (from rust-crypto) based on a configuration string. In Python or JavaScript, say, I'd probably use reflection to get at this: getattr(Digest, myAlgorithm) ...but from what I've been able to Google, this isn't best practice in a language such as Rust (plus I've...

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

php,inheritance,reflection,traits,trait
I want to exclude all inherited methods from trait(s) from the list that are not overriden in a class So how to know if a class member is inherited from trait? Yes, I can check it like this: if ($trait->hasMethod($methodName) || $ref->getTraitAliases()[$methodName] !== null) { // } But what if...

How to refactor repeated code using reflection

c#,linq,generics,azure,reflection
So I have this large switch statement which is essentially the same code repeated multiple times where the only thing changing is the cast to a specific class. I've been trying to figure out a way to refactor it using reflection so I only have to write it once. switch(provider)...

Reflection doesn't recognize that class is inherited C#

c#,inheritance,reflection,attributes
My Problem is I want to get the data from custom Attributes, I don't know which argutement to give the typeof() Method to take the current type. [AttrN("test1")] [AttrC("test2")] public class cl2 :cl1 { //should find attributes and set fields from base public cl2() : base() { } } public...

Why can't I use Java's getDeclaredMethod() in Processing?

java,reflection,processing
I want to create a simple method queue in Processing and I'm trying to do it with Java's native reflection. Why does getDeclaredMethod() not work in this sample? Is there a way to make it work? Regardless of the variations on it that I have tried, it always returns NoSuchMethodException......

java compilation error when using reflection with templates

java,templates,reflection,compiler-errors
I have this code: private <D extends Object> void foo(D d) throws IllegalAccessException, InstantiationException { d = d.getClass().newInstance(); // Compilation error: "Incompatible types: Required D, Found: Object" } Why do I get this error? To my understanding, the compiler knows that d is D type (which extends Object)...?...

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

reflection,go,generic-programming
How to return a err=nil as reflect.Value? I need to write a swap function to use with reflect.MakeFunc(). //my swap implementation, that call the original function and cache results func swapFunc(ins []reflect.Value) []reflect.Value { //After cache the first return (Offer) of function FindBestOffer(int)(Offer,bool,error), //i need to return the best Offer...

Deserializing Generic Types from a ClassLouder class with GSON

java,json,generics,reflection,gson
I´m trying to parse a JSON file using GSON, the problem is that I´m using a Class that it was previously loaded by ClassLoader. File root = new File("./build/classes"); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class<?> loadedClass = Class.forName("events.Source", true,classLoader); // JSON --> Java "Get the actual type"...

Generic Programming in Go. Avoiding hard coded type assertion

reflection,go,generic-programming
I'm programming a generic cache mechanism and i need to set some attributes in a struct knowing only their reflect.Type, attribute name and reflect.Value to be setted in the attribute, but i can't avoid the type assertion, that makes my code not generic... func main() { addressNew := Address{"New Address...

Get actual class from stack trace element

java,debugging,reflection,stack-trace
Using Eclipse I can set a breakpoint and see current stack trace on debug view: But when I inspect stack trace using Thread.currentThread().getStackTrace(), the information I get is not exactly the same. For example, selected element is JUnitTestClassReference and the correlated one in stack trace (within dashes) is JUnit4TestReference (its...

Java reflection - get field value

java,reflection,field
I try make class which generate new className.java file using reflection. I have problem with Fields value. Here is my test class. public class ClassTest { @Deprecated private int a; public int[] b; private final String c = "Hi"; ... } Method in which I try generate fields. private void...

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

javascript,reflection,typescript
Let's imagine that we have a JavaScript class: var Person = (function () { function Person(name, surname) { this.name = name; this.surname = surname; } Person.prototype.saySomething = function (something) { return this.name + " " + this.surname + " says: " + something; }; return Person; })(); I want to...

Bound mismatch mitigation

java,generics,reflection
Say I have a generic interface: interface SomeInterface<T> { ... } and two implementations: a specific one (perhaps optimised for SpecificClass and its descendents): class SpecificImplementation<T extends SpecificClass> implements SomeInterface<T> { ... } and another catch all one (perhaps which can handle all types but is very inefficient): class CatchAllImplementation<T>...

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

python,reflection,constructor
I have code that looks like the following and I'm trying to refactor it. # Abstract, do not instantiate Base class Base: ... class A(Base): ... def func(): x = A(1, 2, 3) x.x() y = A(4, 5, 6) y.y() z = A(7, 8, 9) z.z() class B(Base): ... def...

Instantiate type-parametrized class at runtime with default constructor

scala,reflection
I want to instantiate a new object with the following classes: class Test[T : ClassTag](val value : T) extends Serializable private object Test { private var testClass : Class[_] = _ def setTestClass(test : Class[_]) : Unit = { testClass = test } def apply[T : ClassTag](value : T) :...

Advantage of using CustomAttributes vs GetCustomAttributes()

c#,.net,reflection,custom-attributes
I noticed today that some new properties had appeared in my intellisense on the System.Type object for my .NET 4.5 projects. Among these was one called CustomAttributes. I was intrigued by this since I previously had understood that GetCustomAttributes was one of the most expensive reflection calls (DynamicInvoke and the...

How to use reflection with Core Data and Swift

ios,swift,core-data,reflection
I'm trying to use reflection in Swift with Core Data entities, but when I execute the following code, my reflected var has only a reference for a super class, it didn't have a reference for any of it's attributes. func printProperties() { let mirror = reflect(self) for var i =...

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

reflection,go,metaprogramming
I need to assuredly check whether a reflect.Type is an error. There is no reflect kind for error. What is the formal/idiomatic manner to check for type error in go reflect? Go Playground Full Example //return map of default values, based on each return type of a function // error...

Create new object knowing reflected type

reflection,go
In function, one of arguments I'm passing reflect.TypeOf(Person) where person is struct with few strings. If another function which accepts this argument, I want to instantiate this empty struct knowing its reflected type. I have tried following ins := reflect.New(typ) //typ is name or passed reflect.TypeOf(Person) But this returns me...

Get private property of a private property using reflection

c#,reflection
public class Foo { private Bar FooBar {get;set;} private class Bar { private string Str {get;set;} public Bar() {Str = "some value";} } } If I've got something like the above and I have a reference to Foo, how can I use reflection to get the value Str out Foo's...

Get id column name from POJO, using reflection

java,jpa,reflection,annotations
@Entity @Table(name="MY_TABLE") public class MyTable{ @Id @Column(name="MY_TABLE_ID") @GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE") @SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE") private Long myTableId; How can I, using reflection, get the primary key column name from my POJO, defined with the javax.persistence.Id annotation? I'd have to find the @Id and then get the name property of the @Column...

Cast object to unknown type

c#,asp.net,reflection
I would like to create a dynamic method that populates a dropdownlist with any object based on the parameters. Here's my code: PopulateDropDownList(ddl, GetList(), typeof(MyClass)); public void PopulateDropDownList(DropDownList ddl, IEnumerable list, Type type) { object obj = Activator.CreateInstance(type); foreach (var item in list) ddl.Items.Add(new ListItem(((obj)item).Name, ((obj)item).ID.ToString())); } Basically, what I...

Generic Programming in Go, Implicit generic type

generics,reflection,go
I need Go to implicitly resolve my struct type, in order to do generic replacement of some attribute. //must replace the attribute with attValue func SetAttribute(object interface{}, attributeName string, attValue interface{}, objectType reflect.Type) interface{} { /// works perfectly, but function SetAttribute needs to know Customer type to do the convertion...

How to get parameter names via reflection in kotlin?

reflection,kotlin
java8 has "-parameters" argument, passed to compiler, what about kotlin ? As I can see, kotlin compiler add @JetValueParameter annotation with param names to parameters, but one is depricated..

Compiler says dynamic property is missing but I can see it

c#,.net,dynamic,reflection,metaprogramming
I'm starting to dive into the world of C# Dynamics and Metaprogramming, and having some trouble. I managed to create a CodeDom tree, and generate the following code: namespace Mimsy { using System; using System.Text; using System.Collections; internal class JubJub { private int _wabeCount; private ArrayList _updates; public JubJub(int wabeCount)...

Is it bad to have an empty attribute class?

c#,reflection,attributes
I have created an attribute which will define which properties have "special" data. My Attribute looks something like this: [AttributeUsage(AttributeTargets.Property)] public class TestAttribute : Attribute { } I don't need anything in the body of the class because all it's doing is identifying the properties. Is this bad practice? If...

How to use reflection to change backup service?

android,reflection
I posted a question about a new behavior of Android 5.1 that disables the Backup Service when setting up a device-owner on a device here... A possible solution could be (I guess) to use reflection to fix the issue: I could find some reflection examples using a particular method in...

Why BindingFlags are called so?

c#,wpf,reflection
Coming from WPF background,just wondering, why BindingFlags in Reflection are called so? What is so "binding" about it?

ClassCastException while trying to get the generic type parameter

java,generics,reflection
I want to get instance of generic using reflection: this.wrapperInstance = ((Class<WRAPPER>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[1]).newInstance(); but I get exception: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType Do not know where is problem, maybe someaone can help me? There is full class code: public class XMLUtils<MODEL extends AbstractModel, WRAPPER extends WraperInterface<MODEL>> {...

Pattern Matching chooses the wrong case if used with ClassTag

scala,reflection,covariance
What is the connection between variance and ClassTags or TypeTags? I have two types T1 and T2, that are used as type params. case class T1() case class T2() I have an abstract class with an invariant type parameter and one subclass, if I want to check the type of...

Listing Scala nested objects methods through Reflection

scala,reflection
I have the following Scala object: object BusinessFacade { /** * Fachada para acesso aos métodos de controle de Usuário */ object Usuario { private lazy val usuarioBC = new UsuarioBC def buscar(id: Long)(implicit s: Session) = { usuarioBC.findById(id) } def inserir(usuario: User)(implicit s: Session) = { usuarioBC.insert(usuario) } def...

Get object by attribute value [duplicate]

c#,reflection,custom-attributes,spring.net
This question already has an answer here: How enumerate all classes with custom class attribute? 4 answers I have a set of classes which implement a common interface and are annotated with a business domain attribute. By design, each class is annotated with different parametrization [Foo(Bar=1)] public class EntityA...

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

c#,reflection
This question already has an answer here: Distinguish class property types through reflection 3 answers I'm using refelection to iterate through the Public properties of a class. foreach (PropertyInfo prop in instance.GetType().GetProperties()) { ...do work This gets me all public properties. However I only want to get Public Properties...

Automatically delegating all methods of a java class

java,reflection,delegates
Say I have a class with many of public methods: public class MyClass { public void method1() {} public void method2() {} (...) public void methodN() {} } Now I would like to create a wrapper class which would delegate all the methods to wrapped instance (delegate): public class WrapperClass...

Static var in protocol and reflection

ios,swift,reflection
Doing basic reflection in Swift, I encountered a couple of road blocks. The first has to do with static var in a protocol. Isn't it the same as requesting the implementation to define a class var? The second has to do with returning the name of the class when it's...

How I can access instance from MethodInfo

c#,.net,reflection
I have a method receiving a function, usually a method. From that function I can access to the method's class and other stuff using MethodInfo. I want to be able to access the instance used, if any, when passing the function/method. Example: MyFunctionReceivingAMethod(new SomeClass().MethodA) I want to access at MyFunctionReceivingAMethod...

Create generic Func from reflection

c#,reflection,delegates
I've specified type in a variable: Type hiddenType. I need to create a Func<T> delegate where T is of type specified in mentioned variable and assign an method: var funcType = typeof(Func<>).MakeGenericType(hiddenType); Func<object> funcImplementation = () => GetInstance(hiddenType); var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method); It doesn't works - because funcImplementation is...

Cost of reflection: WPF

c#,reflection
I have implemented an extension helper to load a WPF usercontrol to a window dynamically. (MyButton is in another assembly). This helper is in a class lib that is used in all my projects. The idea is to save on re-coding this operation and keep the client code cleaner. I...

What is System.Reflection.Module?

.net,reflection,bcl
Just noticed Assembly.LoadModule() in intellisense. I see it returns a reference to the basically undocumented Module class. I know reflection pretty well and I've never heard of modules? What are they? the name is tantalizing. ...

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

c#,.net,reflection
In my code I have some functions that call Type.GetMethod(string, Type[]) on some various static functions of the CLR. Maybe 30 or so different static functions are being looked up in total. But they are being looked up repeatedly and often because the parent functions are being called often. I...

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

c#,reflection,struct
This question already has an answer here: C# using reflection to create a struct 3 answers I'm trying to create an instance of a struct which's datatype is not known at compile time by obtaining and invoking it's parameterless constructor. The following (otherwise rather useless) code snippet shows what...

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

c#,.net,generics,reflection
Consider a method with the following signature: void foo(List<T> myList) ... Let's assume, by using reflection, you need to construct such a function and obtain the PropertyInfo details of the T type parameter. Calling typeof(T).GetProperties(...) should do the trick, so we can add the following line to our method, to...

Dynamically access methods from scala object

scala,dynamic,reflection
In Scala, what's the best way to dynamically call an object and invoke a method using reflection? The method corresponding to the object is to be called but the object name is known dynamically. I was able to instantiate a scala class dynamically from this SO question however I need...

Instantiate a class which implements a generic interface

c#,reflection
I have an interface for specifying GetData method which returns one instance of the class by its ID public interface ILabelData<T> { T GetData(object id); } and also have many different classes those who implements the interface and having members of course: public class BTAC : ILabelData<BTAC> { // members......

Can Java class files use reserved keywords as names?

java,reflection,jvm,.class-file
I'm aware that Java-the-compilable-programming-language is not one and the same as Java-the-bytecode-format-for-JVM-execution. There are examples of things that are valid in the .class format but not in the .java source code, such as constructor-less classes and synthetic methods. If we hand-craft a .class file with a reserved Java language keyword...

Scala Reflection - MethodSymbol erasure warning unless importing universe._

scala,reflection
I have a class with a generic type parameter, and I want to get a reference to the constructor for the generic type. This only works without erasure warnings if I import the entirety of scala.reflect.runtime.universe._, instead of importing into an alias (e.g. "ru"). It is not clear to me...

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

c#,.net,events,plugins,reflection
Note: I need to use .NET 3.5 My test application is in three parts (different projects and different dlls); host-application, plugin-sdk and test-plugin. The host application is a WPF application with an area to load in views from the plugins. Plugins is loaded through Reflection. This part work as supposed....

Java Reflection, extract generic type from method

java,generics,reflection
I have a java method with the following signature: static <ContentType> Map<Object,ContentType> foo(); I want to use reflection to dynamically change the behavior of the method according to ContentType. To achieve this, I must be able to handle ContentType as an object (maybe an instance of java.lang.reflect.Type). Does anyone know...

Creating an instance from assembly throws a memory leak

.net,reflection,memory-leaks
I have a desktop application where i need to load some dll using reflection in a different AppDomain, call a method and unload the AppDomain. I have correctly developed it, however the number of assemblies i need to load and unload has been increased recently, and now, after loading 3...

Obtain non-explicit field offset

c#,.net,reflection,clr
I have the following class: [StructLayout(LayoutKind.Sequential)] class Class { public int Field1; public byte Field2; public short? Field3; public bool Field4; } How can I get the byte offset of Field4 starting from the start of the class data (or object header)? To illustrate: Class cls = new Class(); fixed(int*...