lundi 31 mai 2021

Using getter/setter for property makes it not appear in reflection (mirror)

I've been trying to implement a theme logic for my custom components. I'll use ZFButton as example.

When the app starts I instantiate ZFbutton and set whatever characteristics I want this one theme to have:

let theme = ZFButton()
theme.backgroundColor = .red //UIButton property
theme.cornerRadius = 8 //ZFButton property
theme.borderColor = .green //ZFButton property
theme.borderWidth = 1 //ZFButton property

Then add it to the theme array:

ZFButton.themes.append(theme)

which resides in the ZFButton as follows:

public static var themes = [ZFButton]()

In my ZFButton I have the following property, which allows me to choose from the IB Attributes Inspector which theme I want to use for that particular ZFButton

@IBInspectable public var theme: Int = 0 { didSet { self.setupTheme() } }

And finally, once the theme property is set, setupTheme() is called, in which I attempt to copy the value set from all properties of a given theme to this particular instance of ZFButton. For that I use reflection:

private func setupTheme() {
    
    if ZFButton.themes.count > self.theme {
        
        let theme = ZFButton.themes[self.theme]
        let mirror = Mirror(reflecting: theme)

        for child in mirror.children {
            
            if let label = child.label,
               label != "theme", //check to prevent recursive calls
               self.responds(to: Selector(label)) {
                   
                self.setValue(child.value, forKey: label)
                
                print("Property name:", child.label)
                print("Property value:", child.value)
            }
        }
    }
}

Now I have two problems:

1 - Properties that have setter/getter do not show up in the reflection, example:

@IBInspectable public var borderColor: UIColor {
    
    set { layer.borderColor = newValue.cgColor }
    get { return UIColor(cgColor: layer.borderColor!) }
}

Whereas properties that use didSet do, such as:

@IBInspectable public var iconText: String = "" { didSet { self.setupIcon() } }

However, I do need a getter here to return the borderColor in layer.

2 - When using Mirror to reflect all ZFButton properties, besides the issue described in (1), I don't get UIButton properties either, is there a way to get ZFButton's superclass (UIButton) as well?





Activator.CreateInstance() analogue in Golang

In C#, there's a method CreateInstance of class Activator which allows you to create an instance of the reflected type as it is shown here.

Is there a way to do the same tihing in Go programming language? I would like to take a type from a plugin (.so on Linux or .dll on Windows) by the name of the type and create an instance of this type in my code. How can I do that?





Use nested reflection to iterate an object that contains objects

as from the title I need to iterate an object using reflection. What do I have:

@Getter
@Setter
public static class ObjectA {
     public ObjectB obj;
}

@Getter
@Setter
public static class ObjectB {
     public String value;
}

String pathValueRetrived = "ObjectA.obj.value";

I have to retrieve the value attribute, obviously in a generic way.

Something like:

String[] pathValue = StringUtils.split(pathValueRetrived, ".");
ObjectA objectA = //retrive the object with values
Object iterator;
for(String idxPath : pathValue){
  if(iterator != null)
      iterator = iterator.getClass().getDeclaredField(path);
  else
      iterator = objectA.getClass().getDeclaredField(path);
}

I thank you very much for your help!





Creating an instance of any class in Java using reflection?

I’m trying to create a program using Java reflection where you pass the name of the class and a list of arguments to the program. The program then takes the list of arguments and uses them to initialise an object of the class.

I’m really lost as to how to go about finding the right constructor to use as it will depend on the list of arguments. Does anyone have any idea how to go about this?





dimanche 30 mai 2021

Is it appropriate to use reflection to create a list of objects of all subclasses?

In my program, different features are divided into different modules, potentially hundreds of modules, each module is a subclass of an abstract Module class which look something like this

public abstract class Module {

    public final String name;

    public Module(String name){
        this.name = name;
    }

    public abstract void execute();
}

with subclasses that look like this

public class Mod1 extends Module{
    public Mod1() {
        super("Mod1");
    }

    @Override
    public void execute() {
        //Do something
    }
}

and I need to make a list of instances of all modules but doing it like this is kinda tedious since my program might have hundreds of modules and it might be hard to debug(I might miss a few lol)

private static final List<Module> MODULES = new ArrayList<>();

public void init(){
    MODULES.add(new Mod1());
    MODULES.add(new Mod2());
    MODULES.add(new Mod3());
    MODULES.add(new Mod4());
    MODULES.add(new Mod5());
}

so I think using reflection might be the way to go but after a quick google search, I see many people don't like reflection in production code, so I come here to ask if this is an appropriate case to use reflection or is there any reason or design change to avoid using reflection in this particular case

edit: the list will be used stuff like rendering modules in gui or calling execute method of the module from other user interface like command(simply find the module with matching name and execute it)

note: this is not how my code actually look like but a highly simplified version that give a similar idea





samedi 29 mai 2021

Is it possible to distinguish identical function calls in Kotlin?

I'm building a library and I want the library to be able to distinguish the different times when the user in his code calls the functions in my library. For example, if I have a function sayHello() defined like so:

fun sayHello() {
    when(idOfFunctionCall) {
        0 -> println("First call!")
        1 -> println("Second call!")
        else -> println("Some other call!")
    }
}

I want this function to be able to detect the different places in the user's code where this function was called.

// user's code
fun main() {
    sayHello()
    
    repeat(3) {
      sayHello()
    }
    
    sayHello()
}

This code should print:

First call!
Second call!
Second call!
Second call!
Some other call!

Is that even possible? I'm planning on using the Kotlin Reflection set of tools but I'm not sure if it is possible.





Creating a delegate of an instance method where the instance is variable

I've been struggling a bit with a tricky scenario. Let's get into it.

This question is similar to my issue. The difference is that I need to build the delegate only once, allowing the instance (target) to be many different values. In other words, I will not have any way to access an instance at the time the delegate is built.

If I can convert the instance MethodInfo into an extension MethodInfo, that would suit my needs.

The question is done here, but there's more context below:

What I'm working with is server software (Specifically DarkRift for Unity) where data is sent by reading and writing to a stream (DarkRiftReaders and DarkRiftWriters). There is the option to implement IDarkRiftSerializable and define methods Serialize(event with writer) and Deserialize(event with reader). I'm writing a class that automatically generates those methods through reflection (Gets all fields of the derived class, uses them to build instructions on how to serialize and deserialize).

I have two methods that take in a type parameter and return a delegate to serialize or deserialize data of that type. These methods search both built in methods of the reader and writer types, along with extension methods.

Here's a snippet of the deserializer method for context:

// GetReader - expensive method, only run once to build the deserializer. 
// Searches assemblies for suitable methods and passes them back to the deserializer.
// Methods = built in methods, Extensions = extension methods loaded

...
var method = Methods.FirstOrDefault(m => m.ReturnType == type);
if (method != null) return reader => method.Invoke(reader, null);

method = Extensions.FirstOrDefault(m => m.ReturnType == type);
if (method != null) return reader => method.Invoke(null, new object[] { reader });
...

Currently they use MethodInfo.Invoke but I would much prefer they return a delegate created by the MethodInfos for optimization's sake.

I'm open to any discussion on this.





vendredi 28 mai 2021

Reflection: How to infer a method's generic type parameters?

In C# you can call a generic method via reflection with code like this:

public class Sample {
    public void Foo<T>() { Console.WriteLine(typeof(T).Name); }
}

MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.Foo));
MethodInfo generic = method.MakeGenericMethod(typeof(int));
generic.Invoke(new Sample(), new object[0]);

I want to do something more complicated: generic parameter inference, or something similar to overload resolution. I want a Resolve method that figures out the generic type parameters in order to construct an instantiated generic method:

public static MethodInfo Resolve(MethodInfo genericMI, params Type[] argTypes)
{
    // for example, if genericMI is a reference to 
    // `Sample.Foo2<,>` (below) and argTypes is 
    // `new[] { typeof(List<(int, float)>) }`, this 
    // method would return a `MethodInfo` for 
    // `Sample.Foo2<int, float>`. But how?
}

public class Sample {
    public void Foo1<T>(IEnumerable<T> data) { }
    public void Foo2<T, U>(IEnumerable<(T, U)> data) { }
    public void Foo3<T, U>(IEnumerable<U> list, (T, U) tuple) where U: struct { }
}

// EXAMPLES:
// Returns MethodInfo for Foo1<(int, float)>
var foo2 = Resolve(typeof(Sample).GetMethod("Foo1"), typeof(List<(int, float)>));

// Returns MethodInfo for Foo2<int, float>
var foo2 = Resolve(typeof(Sample).GetMethod("Foo2"), typeof(List<(int, float)>));

// Returns MethodInfo for Foo3<int, byte>
var foo3 = Resolve(typeof(Sample).GetMethod("Foo3"), typeof(List<byte>), typeof((int, byte)));

// Returns null
var failA = Resolve(typeof(Sample).GetMethod("Foo3"), typeof(List<byte>), typeof((int, float)));

// Returns null
var failB = Resolve(typeof(Sample).GetMethod("Foo3"), typeof(List<Regex>), typeof((int, Regex)));

If it makes things simpler, for my application I only need to resolve these type parameters based on a single parameter (although the target method actually takes two parameters).

Why I'm asking this question

I'm writing a serialization system in which users can "plug in" serializers for specific types. But I think users should be able to provide generic methods that can handle families of types like UserType<X,Y>. So my system will have a list of generic methods (from multiple user-defined classes), and I need to figure out which one of the methods is actually possible to call given the parameter type:

public static MethodInfo Resolve(MethodInfo[] genericMIs, params Type[] argTypes)
{
    foreach (var mi in genericMIs) {
        var resolved = Resolve(mi, argTypes);
        if (resolved != null)
            return resolved;
    }
    return null;
}

I will then construct a delegate via Delegate.CreateDelegate(..., resolved) and use some other tricks to cache the delegate and invoke it like a normal method to achieve good performance, as the same delegate will often be re-used to serialize or deserialize thousands of objects.





How to set the value of a field of type time.Time as time.Now() using reflect in Golang

I have a struct of type

type test struct {
    fname string
    time time.Time
}

I want to set the value of the field "time" as time.Now() using reflect package only.

I am creating a function something like this one:

func setRequestParam(arg interface{}, param string, value interface{}) {
    v := reflect.ValueOf(arg).Elem()
    f := v.FieldByName(param)
    if f.IsValid() {
        if f.CanSet() {
            if f.Kind() == reflect.String {
                f.SetString(value.(string))
                return
            } else if f.Kind() == reflect.Struct {
                f.Set(reflect.ValueOf(value))
            }
        }
    }
}

what I am trying to fix is this expression f.Set(reflect.ValueOf(value)), I am getting an error here.





Listing all the properties in a Kotlin class excluding the ones with custom getters

Is there any simple way to list all the properties in a class excluding the ones with custom getters?

For example in this case:

class Person(val name: String, val age: Int) {

    val signature: String get() = "$name - $age"
    
    val uuid = UUID.randomUUID()
}

I would like to find: [ Person::name, Person::age, Person::uuid ].





Using reflection or other method to analyse tests

I am not sure if is it possible (Google is saying that not really). I want to create test that will analyse other tests for looking some specific elements like annotation, specific class or other and if something is not good then will fail. How should I analyse tests for looking unwanted elements? Lets say I have unit tests but some programmer used spring context to create context what is weird situation, but I want to catch it. Sorry for my english, I am not native.

@Edit hard to provide specific example but I will try.

Lets say I want to achive something like that:

@Test
void checkIfUnitTestsAreCorrect() {
    // how can I check if tests with @UnitTest build SpringContext?

}

@Test
@UnitTest
void unitTest() {
  // SpringContext is building here so it is wrong
}




jeudi 27 mai 2021

retrieve implicitly assigned dispId values for all members in an interface

Given a c# assembly that has ComVisible=true, how would you go about retrieving a list of the implicitly-assigned dispIds within a type? I've discovered we can use reflection or a disassembler to get an explicitly-defined dispIds, but what about the implicit ones?

The overall goal is to get the implicit dispIds of an older version of an assembly so we can explicitly define them in all future versions without breaking compatibility with existing consumers.





JUNIT: ReflectionTestUtils : I need to inject a class in a super class for testing

I am testing a class A that extends an abstract class B. Class B has a private member M which i want to set for testing.

  1. First part of the problem as i understand is to retrieve the class b from class A. For which i tried getSuperclass, which i think may not be the right way to do this. Although, I am able to retrieve the field desired using ````ReflectionTestUtils.findfield()``` but not able to use set field.
  2. Secondly when i try to set field (ReflectionUtils.setField(field_M, B, M_to_be_set)) it basically ends up in the following exception: java.lang.IllegalArgumentException: Can not set M field M to java.lang.Class I have tried to setField, but it is not able to find the field itself.

Thanks





How to pass type value to a variable with the type reflect.Type Golang

I need to create StructField, in which I need to pass reflect.Type value for the Type field. I would like to pass other types like reflect.Bool, reflect.Int to function which will be used in the construction of StructField. I cannot do this with the code below

reflect.StructField{
            Name: strings.Title(v.Name),
            Type: reflect.Type(reflect.String),
            Tag:  reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
        }

Because it

Cannot convert an expression of the type 'Kind' to the type 'Type'




Unity C# Reflection Get/Set Issue

I just can't get this working, so maybe someone can support.

I want to set the value of a specific component field programatically. Here is my code for that (Log_temp is the component):

                FieldInfo info = Log_temp.GetType().GetField("Driver_" + tour.Driver);
                TypedReference infoStructRef = __makeref(Log_temp);

                JSON Tour_Json = JSON.Serialize(tour);

                info.SetValueDirect(infoStructRef, Tour_Json.CreateString());

This works perfectly fine. Now I wanted to not only set the value, but ADD the (string) value to the existing value in the field. Here is what I tried:

            FieldInfo info = Log_temp.GetType().GetField("Driver_" + tour.Driver);
            TypedReference infoStructRef = __makeref(Log_temp);

            JSON Tour_Json = JSON.Serialize(tour);

            info.SetValueDirect(infoStructRef, info.GetValueDirect(infoStructRef).ToString() + Tour_Json.CreateString());

I tried a few other approaches but either I get an error or nothing changes. Could someone help me with this? Thanks a lot!





Couldn't unmarshal xml to a dynamically created struct using reflection in Golang

This is my code for parsing xml. At the end of the function, I should have values of fields of a struct in the values slice.

func FindAttrs(attrs []Tag, errorChan chan<- error) {
    var tableFields []reflect.StructField
    for _, v := range attrs {
        tableFields = append(tableFields, reflect.StructField{
            Name:      strings.Title(v.Name),
            PkgPath:   "utility",
            Type:      reflect.TypeOf(""),
            Tag:       reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
            Offset:    0,
            Index:     nil,
            Anonymous: false,
        })
    }
    unmarshalStruct := reflect.Zero(reflect.StructOf(tableFields))
    err := xml.Unmarshal(ReadBytes(errorChan), &unmarshalStruct)
    HandleError(err, "Error parse config", false, errorChan)
    values := make([]interface{}, unmarshalStruct.NumField())
    for i := 0; i < unmarshalStruct.NumField(); i++ {
        values[i] = unmarshalStruct.Field(0).Interface()
    }
}

But, it panics with the following message:

reflect.Value.Interface: cannot return value obtained from unexported field or method

I call it with:

utility.FindAttrs([]utility.Tag{
        {"name", reflect.String}, {"isUsed", reflect.String},
    }, errorChan)

And my xml is <configuration name="mur" isUsed="mur"/>





mercredi 26 mai 2021

Julia: Generate code at runtime and store it for future evaluation/execution

In Julia, how one can generate arbitrary code to serialize it into a file for future execution under completely different program instance? Is it even possible? Is there a need to store any current context for future execution?





Parsing a string formula by injecting object values (i.e. using reflection) in C#

I need to parse a formula in string format which can contain objects and properties.

Example:

"Person1.Age > 20" or "Person1.Age > RentalCar5.MinimumAge"

Where Person1 would be an object of type Person, and RentalCar5 an object of type RentalCar.

I have the objects, so can check the formula contains "Person1" and know it to be a Person object matching that specific Name property, so I need to then determine the Age property value, then replace the whole "Person1.Age" section with the age, such as 21.

Once this is done it would be easy enough to resolve the formula as "21 >20"

Any thoughts or ideas?





How to get the specified value from a List

Let's say if we have a Container class with generic array

public class Container<T>
{
    public T[] ObjectArray = new T[];
}

public class PlayerInfo
{
    public int level;
    public string playerName;
    public string description
}

public class EnemyInfo
{
    public string enemyName;
}

Now I have Container<PlayerInfo> and Container<EnemyInfo> in my app, which have lots of player/enemy data.

I want to create a List to handle all Container in my app, and print out all fields with string type, how could I achieve it?

Take the above example I want to print out playerName description enemyName.

What I've tried is like this.

//let container inherit from a class
public class Container<T> : BaseClass
{
    public T[] ObjectArray = new T[];
}

//so that I could add them to a single list.
var list = new List<BaseClass>();
list.Add(playerContainerInstance);
list.Add(enemyContainerInstance);

foreach(var element in list)
{
    //and what should I do now to get string field from it?
}

For now I can figure out is do something with reflection, but maybe there is another way to do this?





C# Reflection : How do I access an array's value if it is an object?

Let's say if we have a class containing an array:

public class MyClass<T> : BaseClass
{
    public T[] ObjectArray = new T[100];
}

And I want to access the ObjectArray value by reflections:

// instance1 = MyClass<string>
// instance2 = MyClass<int>
var list = new List<BaseClass>{ instance1, instance2 };
foreach(var element in list)
{
    var arrObj = element.GetType().GetField("ObjectArray").GetValue(element);
    //...and what to do now if I want to access the value in ObjectArray ?
}




mardi 25 mai 2021

SetValue x SetValueDirect, when is it best?

Using the SetValue() method, I need to box my object type, with SetValueDirect() I need to create a reference using the keyword __makeref() (which is not recommended or documented, but you can use it), but I don't need to box, so my question which is the best and the fastest and what is the difference between the two?





Duplicating the signature of a method at compile time in Rust

In my project I have a trait called Processor, which looks like this (Frame is another trait that abstracts over arrays of numerical samples of any size):

use crate::Frame;

pub trait Processor<const NI: usize, const NO: usize> {
    type Input: Frame<NI>;
    type Output: Frame<NO>;

    fn process(&mut self, input: Self::Input) -> Self::Output;
}

In the same module, I have a number of structs that implement Processor, each with varying fields and behaviors. However, each one has a new method for creating an instance. For example, here's the Map struct along with its new method and Processor/From impls:

pub struct Map<FI, FO, M, const NI: usize, const NO: usize>
where
    FI: Frame<NI>,
    FO: Frame<NO>,
    M: FnMut(FI) -> FO,
{
    pub(super) func: M,
    pub(super) _marker: std::marker::PhantomData<(FI, FO)>,
}

impl<FI, FO, M, const NI: usize, const NO: usize> Map<FI, FO, M, NI, NO>
where
    FI: Frame<NI>,
    FO: Frame<NO>,
    M: FnMut(FI) -> FO,
{
    pub fn new(func: M) -> Self {
        Self { func, _marker: Default::default() }
    }
}

impl<FI, FO, M, const NI: usize, const NO: usize> Processor<NI, NO> for Map<FI, FO, M, NI, NO>
where
    FI: Frame<NI>,
    FO: Frame<NO>,
    M: FnMut(FI) -> FO,
{
    type Input = FI;
    type Output = FO;

    fn process(&mut self, input: Self::Input) -> Self::Output {
        (self.func)(input)
    }
}

Also in my project, I have another trait called Signal, these are streams of Frames that behave similarly to the stdlib Iterator. It makes sense to be able to "plug in" a Processor into a Signal to transform it; indeed, I already have such a method defined on Signal:

pub trait Signal<const N: usize> {
    type Frame: Frame<N>;

    fn next(&mut self) -> Option<Self::Frame>;

    fn process<P, const NO: usize>(self, processor: P) -> SigProcess<Self, P, N, NO>
    where
        Self: Sized,
        P: Processor<N, NO, Input = Self::Frame>,
    {
        // This is a new `Signal` type.
        SigProcess { signal: self, processor }
    }
}

For ergonomics, I'd love to be able to have the user avoid having to import Map/Processor and dealing with its semantics, so I'm planning on adding a map method to Signal itself:

pub trait Signal<const N: usize> {
    /* PREVIOUSLY SHOWN CODE */

    fn map<FO, M, const NO: usize>(self, func: M)
        -> Process<Self, Map<Self::Frame, FO, M, N, NO>, N, NO>
    where
        Self: Sized,
        FO: Frame<NO>,
        M: FnMut(Self::Frame) -> FO,
    {
        let processor = Map::new(func);
        self.process(processor)
    }
}

Whew, that was a lot of build up. Now here's the main question I'm asking: how can I programatically add these methods to the Signal trait at compile time for every Processor implementor I have? As can be seen, creating a Signal::map that bakes in an instance of Map is pretty straightforward: Map::new requires a func: M as input, as does Signal::map (self aside). But it's a LOT of boilerplate code, and it's going to be a pain to manage once I end up with the dozens of Processors in the final version, each of which will need to have a separate corresponding method in Signal.

I'm at a loss as to how to approach this, given:

  1. The complexity with type and const generics, especially since I might have to merge or rename type/const vars.
  2. Not knowing how to do code reflection in Rust, or if it's even possible! I'd need to effectively be able to ask the compiler "please look in the processors module, get a list of all types that impl Processor, and for each one: copy the signatures and generics for the new method and insert a new method in the Signal trait".
  3. If there is a way to approach this with something like procedural macros, I'd have to learn them from scratch, but I'd be willing to do so if it's possible to make this work.

Any advice would be greatly appreciated!





MethodBase.Invoke with Convert.ChangeType object result

I have the following code:

Type type = Type.GetType("System.Int16");
object number = Convert.ChangeType("-9", type); //m_value = 3096
MethodInfo method = typeof(Math).GetMethod("Abs", new[] { type });
object resultWithoutCast = method.Invoke(null, new[] { number }); //m_value = 3096
var resultWithCast = (Int16)resultWithoutCast; //9

I'm not sure I know what "m_value" is. My guess is a memory location? What I'm trying to accomplish here is to get the value 9 from resultWithoutCast object, dynamically, without having to cast to Int16.

Thoughts?





lundi 24 mai 2021

What's the alternative to Camel BeanInvocation in camel 3.6.0

I am migrating our project from Camel 2.24.1 to 3.6.0. In the code we use BeanInvocation, where we mention the method that was being called in the bean and other classes inside the method.

The org.apache.camel.component.bean.BeanInvocation is deprecated post 2.24.2.

Is there any alternative approach to achieve this.

public void buildRequest(Exchange exchange) {
 BeanInvocation beanInvocation = new BeanInvocation();
 beanInvocation.setMethod(ExampleBean.class.getMethod("methodName", param1, param2);
    
 ....
 ....
 // Add the arguments to the bean invocation
 beanInvocation.setArgs(args);

 // Set the bean invocation object as the message body
 exchange.getIn().setBody(beanInvocation);
}

P.S: I am new to camel and trying to understand the concepts.





Services registered with Scrutor don't have implementation instance

I was trying to get it to work for about 6 hours and I don't know what is wrong. Anyway:

I want to register all domain events listeners from application and call given methods if any of the domain events occurs.

Startup:

        services.Scan(scan => scan
            .FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
            .AddClasses(c => c.AssignableTo(typeof(IDomainEventListener<>)))
            .AsImplementedInterfaces()
            .WithSingletonLifetime());

Domain event bus:

public void Raise<T>(T args) where T : IDomainEvent
    {
        _serviceCollection.Where(s => s.ServiceType == typeof(IDomainEventListener<T>))
            .ToList()
            .ForEach(s =>
            {
                var descriptor = s;
            });
    }

What I mean by "Implementation instance" is that I can't get object which should be assigned to given IDomainEventListener. (s is ServiceDescriptor from ForEach given in code snippet above).

enter image description here

So my question is: What I'm doing wrong or how can I get object instance which implements interface of given type?





How can I check for an expected type of a field in a type in TypeScript?

How can I check for an expected type of a field in a type in TypeScript?

E.g. I have the

class Foo {
    myField: number | undefined;
}

const a : any = { myField: "2" };

const func = (b: Foo) => {
    //here I want to check if Foo.myField is a number
    //and if it is a number, then I will run the code:
    //b.myField = +b.myField
    //I hope to find something along the same lines as:
    //if(Foo.myField is number) {}
    return JSON.stringify(b);
}

console.log(func(a));

I want to check if the b.myField is supposed to be a number and cast it to a number before stringifying it.

In real world I have that problem, because I can not change the code which generates the a, but I have a lot of fields which are stringified as strings, while actually they should be numbers. So, I do not want to type manually for each field something like this:

if(b.myField) {
    b.myField = +b.myField;
}

So, I want to somehow be able to find out that the Foo.myField is a number.

And my ultimate goal (to avoid the x-y problem) is to have the {"myField":2} as an output from the console.log instead of the {"myField":"2"}.





dimanche 23 mai 2021

How can I restrict one partial class from getting compiled in C sharp?

Suppose there are 3 developers A, B, and C working on a project and are working on the partial class 'Sum' in dot net. Now, I don't want any one developer code of partial class from getting compiled. Is there any way to do so?





Most appropriate data structure to save reflection data

What would be the most appropriate data structure to save data collected using reflection? I would like to reflectively collect various data about classes (Java) and store them inside some kind of data structure, so later this data can be used. Example of collected data would be Modifiers, fields, methods, relations...

Thank you





Which .NET Obfuscator works well with Option Strict Off (late binding in VB.NET)

Obfuscation techniques are a reasonably good way to make it harder for parties to copy algorithms from your code, but certainly not impossible.

But just like flu vaccines, even when they're just 30-40% effective, still better than no protection.

Anyway, I found out that for .NET projects where late binding is used (and in VB.NET, when Option Strict is Off), obfuscation protection can be much reduced with some (or most/all?) obfuscators?

For example this amazing obfuscator: https://help.gapotchenko.com/eazfuscator.net/36/troubleshooting/option-strict-off-compatibility-for-vb-net

from what I understand uses reflection extensively when analyzing the code for obfuscation, and when Option Strict is Off will not rename most if not all of the class members thus losing a critical part of obfuscation protection. (renaming with nonsensical names/character can make it significantly harder to figure out a complex underlying algorithm).

Are there .NET obfuscators that are (a lot more) tolerant of late binding and Option Strict being Off? (c# and other .net languages will cause the same issues when late binding is used)

Eazfuscator is very good at NOT breaking your code after extensive obfuscation, an excellent product in my opinion, but unfortunately it has this limitation.

Hopefully there is another good obfuscator (that isn't idiotically expensive, looking at you ...;) that works well with late binding / Option Strict Off (and Option Explicit On).





samedi 22 mai 2021

Adding dynamic properties to a class that is bound to UI in WPF app via DataTemplate (dynamic properties that are specific to an instance)

I have a WPF application. I have A Person Class that looks as following:

 public class Person
{
    public Person(string id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
    }

    public string Id { set; get; }

    public string Name { set; get; }

    public int Age { set; get; }


}

In my view model, I have an

public ObservableCollection<Person> People { get; set; }

And my View looks as following:

    <Grid>
    <ItemsControl x:Name="DynamicPeople" ItemsSource="{Binding Path=People}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Background="Gray" Margin="6">
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Id"/>
                        <Label Content="{Binding Path=Id}"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Name"/>
                        <Label Content="{Binding Path=Name}"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Age"/>
                        <Label Content="{Binding Path=Age}"/>
                    </StackPanel>
                    <Button Width="120" Height="60">Add New Property</Button>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

When running the app, we get:

enter image description here

Now, the requirement is that upon clicking on the Add New Property button, a pop up will open, and there the user will fill in the Property name, Property type and Property Value. Once the user clicks "Apply" at the popup, we are back to the shown view, and the new property should be added to data template. For example, if the user has filled in at the popup for Adam:

Property name: occupation

Property type: string

Property value: "Teacher"

Then, upon clicking on the Apply button at the popup, we will get:

enter image description here

Note that it's like a property of:

public string Occupation { get; set; }

was added to the Person class, but only to the first instance of Adam.

I have a few ideas, but what is the best approach for implementing something like this?

I think about declaring a model class called DynamicProperty:

    public class DynamicProperty
{
    public string Name { set; get; }

    public Type Type { set; get; }

    public object Value  { set; get; }
}

Then, I would add to the person class:

public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }

This would represent the dynamic properties that as I've mentioned that are specific to an instance of class person.

Then I'm not sure how to edit the data Template to display the newly added properties in a similar way to the existing one (like Name & Age).

I don't like something about my approach, maybe you have any better ideas? Thank you!





Cast func parameter type to object type

I have the following func:

var instance = new MyInstance();
var method = instance.GetType().GetMethod("MyMethod");
Func<bool, PropertyInfo, string, MyClass, object> myFunc = CreateFunc(instance, method);

private static Func<bool, PropertyInfo, string, MyClass, object> CreateFunc(
    object instance,
    MethodInfo method)
{
    var propertyHandlerInterface = instance.GetType().GetInterface(typeof(IPropertyHandler<>).Name);
    var valueType = propertyHandlerInterface.GetGenericArguments().First();
    var funcType = typeof(Func<,,,,>);
    var type = funcType.MakeGenericType(
        valueType,
        typeof(PropertyInfo),
        typeof(string),
        typeof(MyClass),
        typeof(object));
    return (Func<bool, PropertyInfo, string, MyClass, object>)Delegate.CreateDelegate(
        type,
        instance,
        method);
}

I can call it like this:

var myValue = true;
var result = myFunc(myValue, somePropertyInfo, "some string", someMyClassInstance);

I need to be able to cast the first parameter bool to object so that the func looks like this...

Func<object, PropertyInfo, string, MyClass, object> myFunc = CreateMyFunc();

...so I can call it like this:

object myValue = true; // <-- This is key, myValue is of type object.
var result = myFunc(myValue, somePropertyInfo, "some string", someMyClassInstance);

How would I achieve this?

I understand that I need to do some casting here, maybe with the help of the Expressions API?

return (Func<bool, PropertyInfo, string, MyClass, object>)Delegate.CreateDelegate(
    type,
    instance,
    method)




vendredi 21 mai 2021

Kotlin - Instance cannot retrieve it's class annotations via myInstance::class.annotations but can with javaClass.annotations

I've encountered strange behaviour when trying to read Class's annotations from an object.

For example:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class MyAnnotation(val value: String) {}


@MyAnnotation("HelloWorld")
class MyClass 

// in test
val obj = MyClass()
println(obj::class.annotations) // DOESN'T finds annotation
println(obj::class.java.annotations) // finds annotation
println(obj.javaClass.annotations) // finds annotation

However, it does find it when I make direct reference to a class like so:

println(MyClass::class.annotations) // finds annotation

Anything I'm missing?





Get private method with reflection in order to pass it to a higher order function in Kotlin

I'm having a hard time trying to get a private method in Kotlin using reflection in order to pass it as a parameter to a higher order function, here is what I got and what I need to do:

The function that gets the private method, probably what I should change or fix:

inline fun <reified T> T.getPrivateFunc(name: String): KFunction<*> {
    return T::class.declaredMemberFunctions.first { 
        it.name == name 
    }.apply { 
        isAccessible = true 
    }
}

This is the high order function I have:

class MyService {

    fun myHigherOrderFunction(action: () -> Unit) { /*...*/ }
}

These are the class and the private method I need to get somehow:

class SystemUnderTest {

    fun privateFunc() { /*...*/ }
}

Finally a unit test where I I'm trying to make sure the proper method is passed to the high order function, I omitted details for simplification:

// ...
val serviceMock = MyService()
val sut = SystemUnderTest()
// Here is what I'm trying to accomplish
val privateMethod = sut.getPrivateMethod("privateFunc")
service.myHighOrderFunction(privateMethod) 
// In the above line I get a compilation error: required () - Unit, found KFunction<*>
service.myHigherOrderFunction(privateMethod as () -> Unit) 
// In the above line I get the following runtime error:
// ClassCastException: kotlin.reflect.jvm.internal.KFunctionImpl cannot be cast to kotlin.jvm.functions.Function1

I know the test can be done having the privateFunc as public and maybe annotating it with @VisibleForTesting, but what I want is to avoid compromising the design as long as I can.

Any ideas? Thanks in advance!





Replacement for sun.reflect.ConstructorAccessor

I am trying to mavenize some old code and I found these two imports:

import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;

Used in this code:

ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();

private static void setFailsafeFieldValue(Field inField, Object inTarget, Object inValue) throws NoSuchFieldException, IllegalAccessException {

    // let's make the field accessible
    inField.setAccessible(true);

    // next we change the modifier in the Field instance to
    // not be final anymore, thus tricking reflection into
    // letting us modify the static final field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    int modifiers = modifiersField.getInt(inField);

    // blank out the final bit in the modifiers int
    modifiers &= ~Modifier.FINAL;
    modifiersField.setInt(inField, modifiers);

    FieldAccessor fa = reflectionFactory.newFieldAccessor(inField, false);
    fa.set(inTarget, inValue);
}

private static ConstructorAccessor getConstructorAccessor(Class<?> inEnumClass, Class<?>[] inAdditionalParameterTypes) throws NoSuchMethodException {
    Class<?>[] parameterTypes = new Class[inAdditionalParameterTypes.length + 2];
    parameterTypes[0] = String.class;
    parameterTypes[1] = int.class;
    System.arraycopy(inAdditionalParameterTypes, 0, parameterTypes, 2, inAdditionalParameterTypes.length);
    return reflectionFactory.newConstructorAccessor(inEnumClass.getDeclaredConstructor(parameterTypes));
}

Since this is a sun.* class and we should not use it, is there a replacement for it? I can't seem to find anything.





Resolving string path through reflection, like WPF binding

I need to be able to resolve a (string) path to a property of a class, like WPF binding does. So something like "MyProperty.MySubProperty.MyList[2].FinalProperty". I do not need to subscribe to changes, I just need to resolve it once to get the value.

Is there any code I can reuse of the WPF framework, or anything else that already exists?





jeudi 20 mai 2021

Generating Java POJO from JSON and using the generated class without having to change code

I'm trying to generate POJO from Json and for that I've found jsonschema2pojo.

But I'd like to use the generated class from my code without having to change my code everytime a new class is generated. I'll receive many different Json's and I'd like to use them as POJO's without interrupting the program.

I also need to access at least a variable from each POJO that might have a different name, for that I was thinking of using Java reflection.

I'd like to know if this is doable, or if there's better ways to implement this.





Checking Struct fields Type using reflect

I am trying to check struct fields using Go reflect package. I have tried it in many ways and found two possible ways. But in the second way i have mentioned in below, complex or custom types can not be checked (example uuid.UUID). Only types that are included in reflect.Kind. Is there any other possible way to check custom type (example uuid.UUID) using reflect ?

First Way run here

 package main
 
 import (
    "fmt"
    "reflect"
 
    "github.com/google/uuid"
 )
 
 type Object struct {
    A string
    B int64
    C uuid.UUID
    D int
 }
 
 func main()  {
    obj :=Object{}
    typ := reflect.TypeOf(obj)
    for i := 0; i < typ.NumField(); i++{
        switch {
        case typ.Field(i).Type == reflect.TypeOf(""):
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.TypeOf(""))
 
        case typ.Field(i).Type == reflect.TypeOf(int64(0)):
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.TypeOf(int64(0)))
 
        case typ.Field(i).Type == reflect.TypeOf(uuid.New()):
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.TypeOf(uuid.New()))
 
        default:
            fmt.Printf("default: type of field %s is %v \n", typ.Field(i).Name, typ.Field(i).Type)
        }
    }
 }

Output:

type of field A is string 
type of field B is int64 
type of field C is uuid.UUID 
default: type of field D is int 

Second Way - replacing switch as below run here

        switch typ.Field(i).Type.Kind(){
        case reflect.String:
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.String)

        case reflect.Int64:
            fmt.Printf("type of field %s is %s \n", typ.Field(i).Name, reflect.Int64)

        default:
            fmt.Printf("default: type of field %s is %v \n", typ.Field(i).Name, typ.Field(i).Type)
        }

Output:

type of field A is string 
type of field B is int64 
default: type of field C is uuid.UUID 
default: type of field D is int 




Java Reflection: How to obtain an instance of Class

What I'm trying to do is to get a generic typearg of a Field using

Type type = f.getGenericType();
if (type instanceof ParameterizedType) {
    ParameterizedType ptype = (ParameterizedType) type;
    // ...
    Class<?> typearg0 = ??? // ptype.getActualTypeArguments()[0]
}

(where f is an instance of java.lang.Field). I need that instance of Class<?> to perform a Foo.class.isAssignableFrom(typearg0) check later, which only takes Class<T>es as an argument. At the same time, I know (or expect) said typearg0 to be a parameterized type as well, so there's a contradiction: typearg0 cannot be Class<?> and ParameterizedType at the same time, because Class<?> is itself a class and does not implement ParameterizedType.

Can I achieve the isAssignableFrom() check in any other way? Or is my goal generally impossible to achieve?

Thank you very much!





How to forbid specific methods (from external lib) in Java?

I could not find much resources on my question so I guess this is not an easy resolution.

We use JodaTime in our codebase and I wish to forbid (or at least warn) using some methods from this library as they are prone to errors (around timezone management).

I tried the reflections library already, without success due to a non released issue. We used to have a custom sonar rule to handle this but it is not supported by sonarcloud so I looking for another way.

Do you have any lead to handle this?





mercredi 19 mai 2021

How to exclude the R class from being obfuscated by ProGuard?

I currently get a list of fonts dynamically via reflection (as I understand it...) using the following method:

com.example.helloworld.R.font.class.getFields();

This breaks when using ProGuard's minify so I've added in the following lines to Proguard-rules:

-keep class com.example.helloworld.R* {
    <fields>;
}

I'm guessing this will end up excluding all classes in my app beginning with R... I tried being as specific as possible using com.example.helloworld.R.font* but it doesn't work.

What should the correct exclusion rule be in this case if I just want the Resource.font class excluded?





Get Property's Type Inside Getter for C#

Is there a way to get the property's type inside of a getter? Like with reflection or something?

public int Age {

    get 
    {
        var myType = {code to get property's type};
               
        //do stuff with myType
    }

}




Constructor with 2 parameters actually has 3

When using reflection to inquire information about the Constructor of a class in runtime.

public class amongUs {
...
...
...
   @Retention(RetentionPolicy.RUNTIME)
   @Target({ElementType.PARAMETER, ElementType.METHOD})
   @interface Message {
   }

   public enum Colors {RED , YELLOW , GREEN ,BLACK , WHITE, BLUE, CYAN, PURPLE, VELVET, BROWN, ORANGE  
   };
   public class Player {

   }
   public class pla extends  Player {
       String color;
       String message = "im not sus";

       @Inject
       public pla(@Message Integer x,@Message String wut) {
           color = (Colors.values()[x]).name();
           message=wut;
       }

   }


...
...
}

However, when I look at the constructor of "pla" it shows it has 3 parameters.

Debugger Description

Why is it happening and how do I fix it?





Getting map entries using reflection in Golang

I want to get maps entries of type <string, interface{}> using reflection. The value of those entries could be of native types (string, int, float, etc.) or Time. I use those maps to allow passing miscellaneous data to error logs. Up till now, I tried using reflect Value, but I cannot execute Value.Interface on those values of type interface{}, so I am not able to get the value. I, also, tried using Value.MapKeys but I was not successful.

The code that I tried was this:

keys := mapValue.MapKeys()
for _, key := range keys {
    mapValue.MapIndex(key)
}

But, the

mapValue.MapIndex(key).CanInterface()

is false. So, I cannot get the value.

How could I get those values from the map?

Update: I was able to have it working using this:

var logFields []log.Field
keys := mapValue.MapKeys()
for _, key := range keys {
    entryValue := mapValue.MapIndex(key)
    logFields = append(logFields, log.String(key.String(), fmt.Sprintf("%#v", entryValue)))
}

The only thing that I cannot get is Time string value.





lundi 17 mai 2021

How can I prove that 2D reflection given by given Matrix?

How can I prove that 2D reflection about the line y=x tan⁡θ, where θ is the angle between the line and the x axis is given by:

[cos⁡2θ sin⁡2θ

sin⁡2θ -cos⁡2θ]





Is there a way to determine the root cause of a system.accessviolationexception?

I've reviewed other questions related to this one and specifically Finding the cause of System.AccessViolationException but perhaps there is something else that could be looked at.

I have a powershell script, running under psversion v5.1 on windows 10 1909, that consistently crashes powershell with this exception when it attempts to retrieve the user's kerberos TGT using the following call:

$SUCCESS = $Secur32::LsaCallAuthenticationPackage_KERB_QUERY_TKT_CACHE($LsaHandle, $AuthenticationPackage, [ref]$ProtocolSubmitBuffer, $KERB_QUERY_TKT_CACHE_REQUEST::GetSize(), [ref]$ProtocolReturnBuffer, [ref]$ReturnBufferLength, [ref]$ProtocolStatus)

If I run the script interactively either in the powershell console or ISE it runs without issue and retrieves the user's TGT. When the same script is invoked through a batch process running under the same user it gets the following .net exception in the event viewer.

Application: powershell.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.AccessViolationException at Kerberos.secur32.LsaCallAuthenticationPackage_KERB_QUERY_TKT_CACHE(IntPtr, UInt64, KERB_QUERY_TKT_CACHE_REQUEST ByRef, UInt64, IntPtr ByRef, UInt64 ByRef, UInt32 ByRef) at DynamicClass.CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Object, System.Object, System.Object, System.Management.Automation.PSReference, System.Object, System.Management.Automation.PSReference, System.Management.Automation.PSReference, System.Management.Automation.PSReference) at System.Dynamic.UpdateDelegates.UpdateAndExecute8[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Runtime.CompilerServices.CallSite, System.__Canon, System.__Canon, System.__Canon, System.__Canon, System.__Canon, System.__Canon, System.__Canon, System.__Canon) at System.Management.Automation.Interpreter.DynamicInstruction9[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.Interpreter.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.LightLambda.RunVoid1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.__Canon) at System.Management.Automation.PSScriptCmdlet.RunClause(System.Action1<System.Management.Automation.Language.FunctionContext>, System.Object, System.Object) at System.Management.Automation.PSScriptCmdlet.DoEndProcessing() at System.Management.Automation.CommandProcessorBase.Complete() at System.Management.Automation.CommandProcessorBase.DoComplete() at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(System.Management.Automation.CommandProcessorBase) at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(System.Object) at System.Management.Automation.PipelineOps.InvokePipeline(System.Object, Boolean, System.Management.Automation.CommandParameterInternal[][], System.Management.Automation.Language.CommandBaseAst[], System.Management.Automation.CommandRedirection[][], System.Management.Automation.Language.FunctionContext) at System.Management.Automation.Interpreter.ActionCallInstruction6[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.Interpreter.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.LightLambda.RunVoid1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.__Canon) at System.Management.Automation.PSScriptCmdlet.RunClause(System.Action1<System.Management.Automation.Language.FunctionContext>, System.Object, System.Object) at System.Management.Automation.PSScriptCmdlet.DoEndProcessing() at System.Management.Automation.CommandProcessorBase.Complete() at System.Management.Automation.CommandProcessorBase.DoComplete() at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(System.Management.Automation.CommandProcessorBase) at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(System.Object) at System.Management.Automation.PipelineOps.InvokePipeline(System.Object, Boolean, System.Management.Automation.CommandParameterInternal[][], System.Management.Automation.Language.CommandBaseAst[], System.Management.Automation.CommandRedirection[][], System.Management.Automation.Language.FunctionContext) at System.Management.Automation.Interpreter.ActionCallInstruction6[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.Interpreter.Run(System.Management.Automation.Interpreter.InterpretedFrame) at System.Management.Automation.Interpreter.LightLambda.RunVoid1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.__Canon) at System.Management.Automation.DlrScriptCommandProcessor.RunClause(System.Action1<System.Management.Automation.Language.FunctionContext>, System.Object, System.Object) at System.Management.Automation.DlrScriptCommandProcessor.Complete() at System.Management.Automation.CommandProcessorBase.DoComplete() at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(System.Management.Automation.CommandProcessorBase) at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(System.Object) at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper() at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc() at System.Management.Automation.Runspaces.PipelineThread.WorkerProc() at System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Threading.ThreadHelper.ThreadStart()

I've attempted to attach the PS debugger to the script process and all the variables are set correctly before the call and I've reviewed the function signature types, structs, enums, etc. but I'm stumped. Is there anything is this stack trace that can shed some light on the underlying cause?





How to get attribute values from generic type? [duplicate]

I have a custom Attribute (MyAttribute) that has only one property named Name. So I am using in classes.

public class Product{
   
    [MyAttribute("product_name")]
    public string Name { get; set; }

    [MyAttribute("product_price")]
    public decimal Price { get; set; }
}

So I have a method to get attribute values and join them.

    public static IEnumerable<string> Method<T>(string separator = ",")
    {

        PropertyInfo[] properties = typeof(T).GetProperties();

        yield return string.Join(separator, properties
               .Where(p => p.GetCustomAttribute<MyAttribute>() != null)
               .Select(p => p.GetCustomAttribute<MyAttribute>().Name).ToArray());

    }

This works but I want to use as generic the attribute type. But can not get the Name property

    public static IEnumerable<string> Method<T, TAttribute>(string separator = ",")
    {

        PropertyInfo[] properties = typeof(T).GetProperties();

        yield return string.Join(separator, properties
               .Where(p => p.GetCustomAttribute<TAttribute>() != null)
               .Select(p => p.GetCustomAttribute<TAttribute>().??????(Name)).ToArray());

    }




Reflection with Generics

Within an .Net ActionFilter I'm trying to convert the ActionArguments into its concrete type using generics. The param I'm passing in for this particular filter would be something like BaseClass<T> where T: AnotherClass. Is there anyway I can detect what 'T' is and cast my object to that particular implementation at runtime?

Here's what I'm doing now which works but I'd love to get away from using dynamic if possible:

var viewModel = filterContext.ActionArguments["viewModel"];
Type type = filterContext.ActionArguments["viewModel"].GetType();
dynamic concreteViewModel = Convert.ChangeType(entity, type);




How to find the reflection matrix about plane?

How can I find the reflection matrix about the plane: (p-q)⋅n=0 Where q=(q_x,q_y,q_z )∈R^3 is a point on the plane and n=(n_x,n_y,n_z ) is a unit normal vector of the plane?





Simple Java Annotation [closed]

My friend and I would like to create a very simple Java annotation (for methods) which will print something simple for every method which is annotated. For example: “This method is annotated with MyCustomAnnotation” (We would then like to add a few stack-trace elements to this printout, so it needs to be flexible enough for this).

What is the simplest code to achieve this?

Our objective is as follows... invoking the following method:

@MyCustomAnnotation
    public static int sayBlahAndReturnOne() {
        System.out.println("blah");
        return 1;
    }

would give the following output:

“This method is annotated with MyCustomAnnotation”
“blah”

How do we achieve this? What would the @interface annotation look like?





dimanche 16 mai 2021

Can't invoke a method obtained through reflection

I am getting the error

Cannot invoke "Object.getClass()" because "obj" is null

on the line

            m.invoke(null);

Here are the classes:

package device;

public class Conveyor {
    private String ID;
    
    public Conveyor(String ID) {this.ID = ID;}
    
    public void Start() {
        
    }

    public void Stop() {
        
    }

}


package main;

import java.lang.reflect.Method;

import device.Conveyor;

public class Main {
    
    public static void main(String args[]) {
        
        Conveyor myConveyor = new Conveyor("C1");

        Class<Conveyor> conveyorClass = (Class<Conveyor>) myConveyor.getClass();

        for (Method m : conveyorClass.getMethods()) {
            System.out.println(m.getName());
            if (m.getName().equals("Start")) {
                try {
                    m.invoke(null);
                } catch (Exception ex) {
                    System.err.println(ex.getLocalizedMessage());
                }
            }           
        }
    }
}




Get input for unknown class fields during runtime

I've been learning C# the past couple of months and we've been tasked with a small project where there's this specific requirement:

We need to design the UI part of the project in such way, that we can figure out some random class fields and then get the input from a user to initialize those fields.

For example, in one run of the program we have this class A that has two integer fields. In the UI section, we need to figure out class A has two integers, then we need to receive 2 integers from the user and pass them back for initialization.

Another scenario:

We have class B that has a boolean and an Enum field, and we need to do the same.

I've been leaning towards using reflection to gather the data needed in runtime, but I'm having a lot of problem figuring out how to actually receive the required input from user. Another hurdle is that we were told that reflection isn't gonna help us and/or not required to fulfill this task.

I'm fairly inexperienced with the language so I assume there may be some other ways to implement this that I'm not aware of, but conceptually speaking - I really can't grasp how it is possible.

Here's some basic classes hierarchy to give a better example:

public abstract class Shape
{
    private Point location;
    private string color;
}

public abstract class NonCircular : Shape
{
    private int edgesNumber;
}

public class Circle : Shape
{
    private float radius;
    private float diameter;
}

public class Triangle : NonCircular
{
    public enum AngleType { Right, Acute, Obtuse }
    public enum EdgePropery { Equilateral, Isosceles, Scalene }
    private AngleType angleType;
    private EdgePropery edgePropery;
    private float angle1, angle2, angle3;
}

Going with this example - let's say that class 'Triangle' is being added to the solution later-on, after the project is done. We first construct the abstract class 'Shape' with some of the basic fields that are shared among everyone, and then according to the requirements, the UI needs to receive the fields:

angleType, edgePropery, and angles1-3

and pass back values to the logical part of the project in order to initialize them properly.





samedi 15 mai 2021

How do you generate getter and setter methods for private properties in a class in Java using reflection techniques [closed]

How do you generate getter and setter methods for private properties in a class in Java using reflection techniques?i want a example





Predicate member referencing

Compiler converts LINQ function predicates into FieldInfo with names "Predicate`1". I want to analyze these FieldInfo to see which members, if any, are referenced. For example the predicate below uses the user-defined method "ArchName":

list.FindAll(m => !m.ArchName().Contains("<>c"))

I'm not aware that FieldInfo has any related MethodInfo members. What might be done?

Thanks in advance!





Instantising a class via reflection using a constructor with a functional interface

If i have a class, that has a private interface inside, which has the @FunctionalInterface annotation, and a private constructor which takes an instance of a class that implements this interface, how can I construct this object using reflection with my custom implementations of the said interface? For instance:

public class mcve {
  private mcve(mcve.wrapper<String> wrp1, mcve.wrapper<String> wrp2) {
    // ...
  }
  private mcve(mcve.wrapper<String> wrp1) {
    // ..
  }
  public static final mcve INSTANCE_1 = new mcve(ClassExtendsString::new, ClassExtendsString::new);
  public static final mcve INSTANCE_2 = new mcve(ClassExtendsString2::new, ClassExtendsString2::new);
  @FunctionalInterface
  interface wrapper<O> {
    O wrap(O object) throws Exception;
  }
}

and some code trying to accomplish what I want:

 Constructor<mcve> constructor;
 constructor = mcve.class.getDeclaredConstructor(??.class);
 constructor.setAccessible(true);
 mcve testInstance = constructor.newInstance(?? MyCustomClassExtendingString::new);

How do I proceed? The compiler complains about Object not being a functional interface. I'm not sure what to pass to getDeclaredConstructor and newInstance.





Call delegate (func/action) with generic argument in dynamic assembly

I want to create dynamic assembly with generic class:

class TestClass<T> where T : new() {
  public T TestMethod() {
    return f();
  }

  private Func<T> f;
}

So, I created class, added generic argument, set constraints and created delegate like this:

var fieldType = typeof(Func<>).MakeGenericType(TArg); 
// TArg = testClassBuilder.DefineGenericParameters("T")[0];

Then using IL generator I tried to emit calling Invoke method:

ilGenerator.Emit(OpCodes.Callvirt, fieldType.GetMethod("Invoke"));

But I get NotSupportedException on GetMethod("Invoke") call. So, how to call this delegate using Emit?





vendredi 14 mai 2021

Is reflection still inefficient on contemporary JDKs(11+)?

I'm looking to avoid having a ridiculously large switch statement, so instead I've created this method:

private static Map<String, Constructor<?>> constructorCache = new ConcurrentHashMap<>();    
public static Object instantiate(String path, Object... params) {
    
    try {
        Constructor<?> cons = null;
        
        if(constructorCache.containsKey(path)) {
            cons = constructorCache.get(path);
        }
        else {
            Class<?>[]clazzes = new Class<?>[params.length];
            
            for(int a = 0; a != params.length; a++) 
                clazzes[a] = params[a].getClass();
            
            Class<?> clazz = Class.forName(path);
            cons = clazz.getConstructor(clazzes);
        }
            
        
        return cons.newInstance(params);
        
    } catch (Exception e) {
        throw new RuntimeException("Error while instantiating " + path + " Stacktrace: " + e.getStackTrace());
    }
}

Is this bad practice, especially for performance-critical code?





Access package accessible constructor outside package

I knot that it sound a bit controversial, but I must access a constructor that is protected with the package accessor... however I'm outside that package, and so I was using reflection to access that constructor like so:

Constructor<TargetClass> constructor = TargetClass.class.getDeclaredConstructor(SomeClass.class);
var manager = constructor.newInstance(new SomeClass());

However when I run this, I get:

java.lang.IllegalAccessException: class com.mypackage.Application cannot access a member of class com.someotherpackage.TargetClass with modifiers ""

Are there ways to avoid this, or either other ways to access that constructor?





How to get returned properties from Expression

I'm working on a .Net core project targeted .Net 5. I have a method that will receive a parameter his type is Expression<Func<T , object[]>>, inside the method I will loop on all returned properties from the expression.

What I trie :

public virtual void UpdateExcept( TEntity record, params Expression<Func<TEntity , object[]>>[] propertiesToBeExcluded )
{

   //Some logic here

    foreach ( var property in  propertiesToBeExcluded )
    {
        foreach ( var prop in property.GetMemberAccessList() )
        {
          //Here I got the property name (I think)
           var x = prop.Name;
        }
    }
}

More explain: In reality I created this method In a repository based on Entity framework this method should update an TEntity record and ignore (do not update) some sent properties in the propertiesToBeExcluded sometimes I will update a record and ignore one property and in another times I will update one record and ignore many properties.

Originale method logic I tried:

public virtual void UpdateExcept( TEntity record, params Expression<Func<TEntity , object[]>>[] propertiesToBeExcluded )
{
    var entity = Context.Set<TEntity>();
    entity.Attach( record );
    Context.Entry( record ).State = EntityState.Modified;

    foreach ( var property in  propertiesToBeExcluded )
    {
        foreach ( var prop in property.GetMemberAccessList() )
        {
            Context.Entry( record ).Property( prop.Name ).IsModified = false;
        }
    }
}

Example of using for this method:

_studentRepository.UpdateExcept( record : student , propertiesToBeExcluded : x => new object[] {x.Picture} );

Another example:

_studentRepository.UpdateExcept( record : student , propertiesToBeExcluded : x => new object[] {x.CreatedOn, x.CreatedBy} );

This method was in this structure:

public virtual void UpdateExcept( TEntity record, params Expression<Func<TEntity , object>>[] propertiesToBeExcluded )
{
    var entity = Context.Set<TEntity>();
    entity.Attach( record );
    Context.Entry( record ).State = EntityState.Modified;

    foreach ( var property in  propertiesToBeExcluded )
    {
        Context.Entry( record ).Property( property ).IsModified = false;
    }
}

Example of use for the old structure:

_studentRepository.UpdateExcept( record : student , propertiesToBeExcluded : x => x.CreatedOn, x => x.CreatedBy );

Why I changed from the old structure to the new: Cause if you notice in the old structure I have to write many times the x's parameter for the func and I was no idea how to use it one time and return multiple properties.

I wish all this helped you understand the issue, so please any help about this issue ?





Map [name,value] string values to class without reflection

I'm having a huge performance issue about mapping string property names and string property values to classes using reflection.

My issue now:

  public class Person
{
    public string Property1 { get; set; }

    public string Property2 { get; set; }

    public string Property3 { get; set; }

    public string Property4 { get; set; }

    // My class has around 100 properties
    public string Property100 { get; set; }
}

I am mapping a key value pair collection to the class using reflection

[{"Property1": "some value"}, {"Property2": "something else"},{"Property3","Property4","value" }.....{"Property100","val"}]

It got to the point that I am now mapping around 10 000 class instances using reflection and the performance is to say it lightly bad.

Any ideas for eliminating the reflection would be greatly appreciated.





should I use strategy pattern, If I have hundreds of actions

I have a class doing translate job. But it have hundreds of specific translate methods! The action code determine which method will be used! I want to use strategy pattern, but it will create hundreds of sub class! I want to name the methods end of action code and use reflection to do the translate, but I'm concern abort the execution performances. It will be called very frequently! What design pattern or patterns should I use to solve this problem! code like this:

public class Test003_Translate {

public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Test003_Translate translate = new Test003_Translate();
    String prefix = "translate";
    String actionCode = "001";
    Method method = Test003_Translate.class.getMethod(prefix + actionCode);
    method.invoke(translate);
}

public void translate001(){
    ;
}
public void translate002(){
    ;
}
public void translate003(){
    ;
}
...
public void translate200(){
    ;
}

}





jeudi 13 mai 2021

How to use a default Constructor genericly

I wanna activate a default constructor in a generic way.

As in, getting an array of constructors and activating one of them (lets assume the first one is default).

The bit of code i wanna use it in is as so:

  List<Constructor> constructors=
  Arrays.stream(clazz.getDeclaredConstructors()).filter(X->X.isAnnotationPresent(Inject.class)).collect(Collectors.toList());
       if(constructors.size()>1)
                throw new MultipleInjectConstructorsException();
        else if(constructors.size()==0){
                List<Constructor> defaultctor=
                Arrays.stream(clazz.getDeclaredConstructors()).filter(X->X.getParameterCount()==0).collect(Collectors.toList());
                if(defaultctor.size()==0)
                    throw new NoConstructorFoundException();
                else {
                    /**activate the default constructor i got*/
                    //obj=defaultctor.get(0); 
    
                }
            }

How can i use the default constructor which is in defaultctor.get(0)?





Java: Set Different Object Fields Based On Array Size

I have an object that has the following fields:

@Data
public class Person {
    private String code1;
    private String code2;
    private String code3;
    private String code4;
};

Then I need to set those code fields based on an input array size:

 if array has size 1, set code1
 if array has size 2, set code1, code2
 if array has size 3, set code1, code2, code3
 if array has size 4, set code1, code2, code3, code4

I did it using 4 if blocks. Is there a way to do it in a loop so that when there are more code fields to add, I don't need to keep adding the if block? Thanks.





DbContextOptionsBuilder

I have looked at several similar questions here but nothing has helped so far.

I am trying to dynamically create a DbContext based on a type that isn't known until runtime. The DbContext is in another library that I reference in my app. I need to pass a DbContextOptions object to the DbContext's constructor. SO I am creating a DbContextOptionsBuilder and trying to call the UseSqlServer() method passing in a connection string. However I get the error in the title.

Other similar questions always say to add the packages Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer and I have done that but without success.

Here is my code right now:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

private DbContext GetDbContext()
{
    Console.WriteLine("\nGetting DB Context...");

    Assembly LaytonDBSets = Assembly.Load("LaytonDBSets.Core");

    List<TypeInfo> dbContexts = LaytonDBSets.DefinedTypes.Where(t => typeof(DbContext).IsAssignableFrom(t)).ToList();

    foreach (TypeInfo ti in dbContexts)
    {
        Type ctxType = LaytonDBSets.GetType(ti.FullName);

        // Get the DbContextOptions to pass to the DbContext constructor
        Type dbContextOptionsBuilderBase = typeof(DbContextOptionsBuilder<>);
        Type dbContextOptionsBuilderType = dbContextOptionsBuilderBase.MakeGenericType(ctxType);
        dynamic dbContextOptionsBuilder = Activator.CreateInstance(dbContextOptionsBuilderType);
        string connStr = iconfig.GetConnectionString(ti.Name);
        dbContextOptionsBuilder.UseSqlServer(connStr); // ERROR HERE
        var options = dbContextOptionsBuilder.Options;

        dynamic ctx = Activator.CreateInstance(ctxType, args: new object[] { options });

        // stuff to be added...
    }

    // stuff to be added...
}

If there is a batter way to do what I am attempting please let me know, I have never done anything like this before.





mercredi 12 mai 2021

How to create an object of interface value type in go using reflection

I need to make a copy of an object in the function that gets an interface{} as a parameter

func helperFunc(param interface{}) interface{} {

    // creating parameter's object copy
    paramType := reflect.PtrTo(reflect.TypeOf(param))
    cpy := reflect.New(paramType).Elem().Interface()
    
    fillSomeValuesFunc(cpy)

    return cpy
}

The problem is that I want to make helper function for testing reading env vars function. It uses envconfig. envconfig performs two checks here:

    if s.Kind() != reflect.Ptr {
        return nil, ErrInvalidSpecification
    }
    s = s.Elem()
    if s.Kind() != reflect.Struct {
        return nil, ErrInvalidSpecification
    }

How to create the object that will pass the checks?





How do I represent complex Map as parameter argument for Class.declaredMethod parameterType?

I have a private method I need to access from a junit. The method has the following signature:

private String search(Map<String, String[]> params, String userName) 

I have tried the following setup:

Method mockSearch;
Class[] cArg = new Class[2];

cArg[0] = Map<String, String[]>.class  
cArg[1] = String.class;
mockSearch = aClass.getClass().getDeclaredMethod("search", cArg);

Which obviously won't even compile because "cArg[0] = Map<String, String[]>.class" is nonsensical. So I attempted a concrete class for arg 0 like this:

Map<String, String[]> mockMap = new HashMap<>();
cArg[0] = mockMap.getClass();

which threw exception at runtime because of the strictness of the getDeclaredMethod. Here basically is exception snippet:

java.lang.NoSuchMethodException: blah.blah.blah$MyTestClass.search(java.util.HashMap, java.lang.String)

Is there a way to represent a Map<String, String[]> class type that will work? Thanks for ideas.





mardi 11 mai 2021

Loading FluentValidation Dynamically Based On Mapping From A dll

I have a main calculator project in the namespace 'Calculator.Main'. It uses different rules for different clients to calculate tax.

  • Suppose I have 2 client ClientA and ClientB.

  • Each clients demands different rules. So I'll add the validator part into a dll and replace that specific dll after deployment based on each client.

I'm using FluentValidator.

  • The first dll will be in the namespace Calculator.Validators.ClientA
  • The second dll will be in the namespace Calculator.Validators.ClientB

This is an example of a validator

namespace Calculator.Validators.ClientA
{
    public class Validator : AbstractValidator<Modal>
    {
        public Validator()
        {
            RuleFor(p => p.FirstName).NotNull().NotEmpty();
            RuleFor(p => p.LastName).NotNull();
            RuleFor(p => p.Email).EmailAddress();
            RuleFor(p => p.Phone).NotNull();
        }
    }
}

I also have a mapping in database that maps which client need which validator It's like

ClientA -- Calculator.Validators.ClientA
ClientB -- Calculator.Validators.ClientB

How can I accomplish creating an instance of the validator dynamically?





When does reflect type.Size() return 0?

I have some generic code that uses reflection to handle struct fields. These fields may or may not include C types, referenced through Cgo.

One problem I encountered was that those aforementioned C types may be "incomplete structs", for instance: typedef struct unknown u;. This can result in a panic later on in the code.

To avoid situations like this, I want to skip these fields. I found that doing a check on the reflect.Type where Size() returns 0 correctly tells me this:

if myType.Size() == 0 {
    return
}

But I was wondering. are there any other instances where a reflect.Type will return a size of 0? In other words, is it possible any other types be skipped?





Initialize nil pointer when the type is interface{}

I was wondering how to initialize a nil pointer to a struct, when the initialize function receives this argument as interface{}.

How can I make this code work assuming that I will always be sending a pointer, and the type of the argument of the function is strictly interface{}?

type Foo struct {
}

func main() {
    var foo *Foo
    fmt.Println("foo is nil: ", foo)
    initialize(foo)
    fmt.Println("foo should not be nil: ", foo) // foo should be Foo{}, but it is nil
}

func initialize(fooPointer interface{}) {
    reflect.ValueOf(&fooPointer).Elem().Set(reflect.ValueOf(&Foo{}))
    fmt.Println("fooPointer is not nil: ", fooPointer)
}

https://play.golang.org/p/Va0bqXJGhWZ





DataSet and Field names via Reflection using Dictionary

I have a requirement to receive a list of DataSet.FieldName as strings and return a object of the Field value. Data strings come to me as "class.[encapsulatedclass 1].[encapsulatedclass n].FieldName i.e.

"Products.ProductCode" "Products.ProductGroup.GroupName" etc...

I have this which almost does the job ...ish. But my question is at the bottom of the example and is really about Dictionaries and is it possible to gain access to the fields of an encapsulted class directly from the Dictionary.

public class ProductGroup
{
    string GroupName{get; set;}
    string GroupDescription{get; set;}
    ProductGroup(string name, string desc)
    
}   
public class ProductDetails
{
    string ProductCode {get; set;}
    ProductGroup Group {get; set;}
    
    ProductDetails (string Name, ProductGroup fred)
    {
        ProductCode = Name;
        Group = fred;
    }
}

 public static void GetTypeMembers<T>(T xRec, ref Dictionary<string, object> dict)
        {
            Type fType;
            PropertyInfo[] fieldProperties = typeof(T).GetProperties();
            object obj = new object();
            string nameStr = string.Empty; 
            foreach (var fProperty in fieldProperties)
            {
                obj = fProperty.GetValue(xRec, null);
                nameStr = fProperty.Name;
                dict.Add(nameStr, obj);
            }
        }

Main()
{
    string[] WantedDetails = {"Products.ProductCode","Products.ProductGroup.Name"}
    List<object> DataToWorkWith.Add(DoIt(WantedDetails));
}

public object DoIt(string[] WantedDetails )
{
    ProductDetails bert = new ProductDetails("Stuff", new ProductGroup({"G1","Group1"}) )
    Dictionary<string, object> dictProducts = new Dictionary<string, object>();
    GetTypeMembers<ProductDetails>(bert, ref dictProducts);

    object obj = new object();
    string[] Fields = map.ProviderData.Split('+');      //{"Products.ProductCode","Products.ProductGroup.GroupName"}
    foreach (string field in Fields)
    {
        string[] Levels = field.Split('.');         
        int lcount = Levels.Length;

        if (Levels[0] == "Products" && lcount > 1)
        { 
            if (lcount == 2) //great to get "Products.ProductCode" returns "Stuff"
                obj = dictProducts.FirstOrDefault(x => x.Key == Levels[1]).Value;
            
            //but now for the GroupName which really a member of ProductGroup
            for (int i = 1; i < lcount; i++)
            {
                //but "Products.ProductGroup" returns fred a TypeOf(ProductGroup)
                //  GroupName is visible in the dictionary entry but is there a way
                //  of getting GroupName from the dictionary without having to 
                //  cast obj as a ProductGroup and go through refection again
                //  to get GroupName?
                //  we could have a required string of 
                //  "Products.ProductGroup.ClassEncapsulatedInProductGroup.....
                //     YetAnotherEncapsultedClass.FieldName"}
                obj = dictProducts.FirstOrDefault(x => x.Key == Levels[i]).Value;.....
            }
        }
        return obj
   }
}




JAVA: Invoke an AIDL Service method that expects another Interface as a parameter

I am trying to invoke a Service method that expects another Interface as a parameter. I must point out that I need to make this using Reflection without actually knowing the source code. So, using Reflection I got the Interface corresponding to the Service whose methods I need to call. Then I managed to create an object for that Interface. After that I am able to call the functions and for most of them this works, but I have a problem when a parameter is another Interface. For example let`s say we have the following method in IPermissionService:

public void addPermissionRevokedListener(IPermissionRevokedListener listener)

While generating the parameter for this method my code finds 2 possible classes:

IPermissionRevokedListener$Default
IPermissionRevokedListener$Stub$Proxy

Currently it takes the first one and calls the constructor to create the object. Everything seems fine till this point, but then when the call is performed an Exception is thrown:

java.lang.IllegalArgumentException: 
    method addPermissionRevokedListener argument 1 has type IPermissionRevokedListener, 
        got IPermissionRevokedListener$Default

I have been digging around and trying some combinations but I could not find a solution for this. Is there a way to solve this?

For those not familiar with AIDL, this is how usually the Interface part looks like:

public interface IPermissionRevokedListener extends android.os.IInterface
{
    public static class Default implements IPermissionRevokedListener
    {...}
    public static abstract class Stub extends android.os.Binder implements IPermissionRevokedListener
    {
        private static class Proxy implements IPermissionRevokedListener
        {...}
    }
}

Also, one possibility would be to try to connect to the other service and acquire the Interface object, similar to the way the first one was done, but I am not sure how to figure out which Service it is just based on the Interface information. Also, I might end up with pretty much the same problem with the only difference being IPermissionRevokedListener$Stub$Proxy instead of IPermissionRevokedListener$Default since IPermissionRevokedListener$Stub$Proxy is given when acquiring Interface from a bound Service). But, I would like to know if there is the possibility find the Service based on the Interface as well.

Anyway, currently I would be happy if the $Default object can somehow be used.





lundi 10 mai 2021

Could I return a class as return of a method?

My problem is, I created a WebApi in asp.net. My models sent to my repository data from my class Person. But I want to persist in database in two different collections (I'm using MongoDB).

For this purpose I made an static method as it follows:

public static Type ReturnAsCollection(PersonTypeDelegate predicatee) 
        {

            if (predicatee.ToString().Equals(typeof(Infectados).Name.Substring(0)))
                return Type.GetType(typeof(Infectados).Name);
            else 
                return Type.GetType(typeof(Vacinados).Name);
        }

But the return is always null.

So, how could I return a Type in this case? There's another way to validate a class and throw it as a parameter?





Building a filter with Expression trees - accessing inherited properties

In my project, I use expression trees to build filters for database operations. This has worked flawlessly so far, but now some of the data structures have changed and I'm running into the following problem.

Imagine the object structure as:

class ClassA
{
   public ClassB PropertyX {get; set; }
}

class ClassB
{

}

class ClassC : ClassB
{
   public string PropertyY {get; set; }
}

class ClassD : ClassB
{
   public string PropertyZ {get; set; }
}

Now, when the user wants to build a filter, I would receive a dot-separated string, for example "PropertyX.PropertyZ". Which means that the PropertyX of ClassA has to be of type ClassD. But how do I build an expression that accesses this property?

I have found a solution here but it does not seem to work for me, maybe I am trying to use it wrong Expression Tree with Property Inheritance causes an argument exception

I tried to do my own implementation as well (code is not very nice, I was mainly just trying to see if this can even work) and the code still fails with the same exception - it tries to find PropertyZ of ClassB, but ClassB does not have that property defined, ClassD does.

//propertyNames is a list of property names that were originally provided as a dot-separated string
foreach (var propertyName in propertyNames)
{
   //returns all types inherited from the provided base type
   var inheritedTypes = _metadataMappingManager.GetMappedTypes(previousType);

   prop = previousType.GetProperty(propertyName);

   if (inheritedTypes != null)
   {
      foreach (var inheritedType in inheritedTypes)
      {
         var inheritedProp = inheritedType.GetProperty(propertyName);
         if (inheritedProp != null)
         {
            prop = inheritedProp;
            previousType = inheritedType;
            break;
         }
      }

      el = Expression.Property(el ?? parameter, (previousType).GetProperty(propertyName));
   }
   else
   {
      el = Expression.Property(el ?? parameter, (previousType).GetProperty(propertyName));
      previousType = prop.PropertyType;
   }
}




dimanche 9 mai 2021

Order Generic C# list using reflection and enum property

I have a generic method that Order a List of T objects using the name of one of the properties.

This is my class:

public class TeamMember
{
    public string Name { get; set; }
    public TeamRole Role { get; set; }
}
public enum TeamRole
{
    Admin,
    User,
    Client
}

And this is the simplified method

public List<T> Sort(List<T> Items, string SortProperty)
{
    var propertyInfo = Items[0].GetType().GetProperty(SortProperty, BindingFlags.Public | BindingFlags.Instance);

    Items = Items.OrderBy(e => propertyInfo.GetValue(e, null)).ToList();
    return Items;

}

All works with a string property, calling Sort() passing a List and "Name" as SortProperty.

How can I update this method to accept the enum "Role" as SortProperty and OrderBy Role?





Cast numbers to closest fitting type in Go

I am writing a parser and an encoder, and I need to guess the number type that the user supplies in the code. For example, the user inputs 8, without any type cast in code, and i need to convert it to int8, if I put in 0.5, I get float32, and if I put, for example, 5182645, I get an int32. Is there any practical way to accomplish that in Go, or should I just write a big if chain?





samedi 8 mai 2021

Android class loading reflection issue

I'm trying to use reflection to execute a specific method from a class from another package. And this works OK for the following scenario:

  • I install the target package and run my app, works ok.
  • I un-install the target package and install a different version of the same package it also works fine when I run it from my app.

If I don't uninstall target, but I just drag over apk with a different code in the emulator (same target package), my app executes code from the previous version, but if I would run that other app, I see it's a proper version (code\functionality) installed, how is that possible???

Obviously, I'm missing something, but this is what I have at the moment behind my app button click:

//...
Context packageContext = createPackageContext("com.some.package", Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY);
Class<?> otherPackageClass = packageContext.getClassLoader().loadClass("com.some.package.SomeClassName");
Method someMethod = otherPackageClass.getDeclaredMethod("someMethod");
//...

(com.some.package is from that other app)

My guess is that it must be something related to this getClassLoader or createPackageContext, but not sure what.

Is it cached maybe somehow and if yes, how to force it to always use the last installed version?

I also tried looking for something like hot reloading for android reflection etc. but I couldn't find anything that could help me solve this problem.