mardi 31 mai 2022

Call Method by string value from data base

So I have a cell in my Oracle table, its value will be some System function or some Static Property like DateTime.Now.Year.
at the table cell the type is VARCHAR2 in .Net its string.

How can I produce a Generic Code for each case (Property, static Function) to get the value in the string

string str = "DateTime.Now.Year" // the value comes from DataBase
var valueFromDataBase = str.invoke();




Is it possible to use all possible types from reflection as generic type?

I am trying to use reflection to automatically create savedStateHandle for some classes.

fun <T> KProperty1<T, *>.argFrom(handle: SavedStateHandle) = 
    when (this.returnType.javaType) {
        String::class.java -> handle.get<String>(this.name)
        Int::class.java -> handle.get<Int>(this.name)
        Uri::class.java -> handle.get<Uri>(this.name)
        else -> throw RuntimeException("Type not implemented yet")
    }

As you see IF the type is for instance String then I want the return type of get function to be String and when doing it this way I have to define every single case manually.

It would be nice if I could just do something like this.

fun <T> KProperty1<T, *>.argFrom(handle: SavedStateHandle) =
    handle.get<this.returnType.javaType>(this.name)




lundi 30 mai 2022

Why class member property reflection in Kotlin?

In 'Kotlin in Action', it says "if a memberProperty refers to the age property of the Person class, memberProperty.get(person) is a way to dynamically get the value of person.age" with code(10.2.1 The Kotlin Reflection API):

class Peron(val name: String, val age: Int)
>> val person = Person("Alice", 29)
>> val memberProperty = Person::age
>> println(memberProperty.get(person))
29

I can't understand why this example refers to "dynamically" getting the value of property. It just works when I run this code:

println(person.age)

Is there any other case or example of member property reflection?





How to call a sub class using a string variable?

So I have this simple for loop and I want to access a variable of a class

However there are multiple classes so that's how I ended up with for loop.

This is what my code looks like.

for (int i = 0; i<itemId.Length; i++)
{
    Type type = Type.GetType(" " + itemid[i]);
    object instance = Activator.CreateInstance(type);
    Debug.Log(itemResponse.data.Invoke(itemid[i]).name);
}

I am trying to access

itemResponse.data."My String".name

The classes I want to access are.

public class _1001{ }
public class _1002{ }
public class _1003{ }

and so on, is there any way I could do that?

Thanks





vendredi 27 mai 2022

How to return either

Using generics and reflection to do a POST, then process the JSON, then return the correct type with its data.

Problem is that I won't know in advance if the type will be a single object or a list of objects. So my generic return type needs to be either a single thing, or a list of single things. (This is .NET Core 6, so what's why the ! in some places...)

How do I handle this conundrum?

    private static async Task<T> ProcessJsonResponse<TX>(HttpResponseMessage response, 
    string? returnModel = null)
    {
        var result = await response.Content.ReadAsStringAsync();

        if (returnModel != null)
        {
            var type = Type.GetType(returnModel);
            var obj = (T?)Activator.CreateInstance(type!);

            var test = type!.GetMethod("FromJson");
            object[] parametersArray = { result };
            var tim = test!.Invoke(obj, parametersArray);
            if (tim is List<T> nowwhat)
            {
               //can't return List<t> since the return type is T
            }
            return (T)tim!;
        }
        //<snip> other non-relevant code ...
    }




jeudi 26 mai 2022

What's the purpose of fromReflectedMethod and toReflectedMethod in JNI?

I was reading the JNI spec and saw the reflection support methods section.

I don't quite understand what they are used for or what's the intended purpose. Since method ID is looked up using name and signature, don't we already have that information? And if we want to get more details, we can always write a java wrapper. So that cannot be the purpose I thought.





mercredi 25 mai 2022

Golang get value of field on child struct using reflection [duplicate]

I'm trying to write a function on a struct that takes a parameter and returns the value of the field that the parameter points to. I then have several child structs that inherit from the root struct (the one with the function). When calling the method on one of those child structs to get a property that only that struct has, it throws the error panic: reflect: call of reflect.Value.Interface on zero Value. I have created a minimal reproduction here. Is there any way for me to only have the method on the root struct while still being able to get values from a child struct?

Code (same as playground):

package main

import (
    "fmt"
    "reflect"
)

type Parent struct {
}

func (p Parent) Get(name string) any {
    v := reflect.ValueOf(p)
    return v.FieldByName(name).Interface()
}

type Child struct {
    Parent
    Field string
}

func main() {
    child := Child{
        Field: "Hello",
    }
    fmt.Println(child.Get("Field"))
}





How to get default value for runtime object

I did a little reflection code.

var objValue = objType.GetProperty(propertyName)!.GetValue(obj, null);
if (objValue == default) // doesn't work for structures
    continue;

But the equal operator doesn't work for structures. How to fix it?





lundi 23 mai 2022

Get at method parameter attribute in Asp.NET Core ActionFilter through reflection

I have an IAsyncActionFilter and I'm intercepting a Controller Method that has a custom attribute on a parameter.

Controller: public async Task<ActionResult<ThingDto>> FindById([MyCustomAttribute] string id)

ActionFilter: public async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)

I'd like to go from the ActionExecutingContext actionContext to this custom attribute - it feels like I'd go from actionContext.ActionDescriptor.MethodInfo.Signature - but I've rooted around in there for a while and nothing fits the bill. Can anyone help pinpoint where this would end up? I'm not able to find any resources on this particular kind of reflection.





dimanche 22 mai 2022

How to get the property names for `UIFont` (and other UIKit classes)?

This simple code:

func getProperties(object: AnyObject) -> [String] {

    var result = [String]()

    let mirror = Mirror(reflecting: object)

    mirror.children.forEach { property in

        guard let label = property.label else {
            return
        }
        result.append(label)
    }

    return result
}

works for custom classes, e.g.:

class A {

    var one: String
    var two: Int

    init() {
        one = "hello"
        two = 1
    }
}

var a = A()
print(getProperties(object: a))
// prints ["one", "two"]

However the same code for UIFont (and other UIKit classes), returns nothing:

var font = UIFont.systemFont(ofSize: 10)
print(getProperties(object: font))
// prints []

I also tried an old-school extension for NSObject:

extension NSObject {

    var propertyNames: [String] {

        var result = [String]()

        let clazz = type(of: self)
        var count = UInt32()

        guard let properties = class_copyPropertyList(clazz, &count) else {
            return result
        }

        for i in 0..<Int(count) {

            let property: objc_property_t = properties[i]

            guard let name = NSString(utf8String: property_getName(property)) else {
                continue
            }
            result.append(name as String)
        }

        return result
    }
}

And again, it works for my custom classes (if they extend NSobject and the properties are marked as @objc):

class B: NSObject {

    @objc var one: String
    @objc var two: Int

    override init() {
        one = "hello"
        two = 1
    }
}

var b = B()
print(b.propertyNames)
// prints ["one", "two"]

but doesn't find any properties for UIFont.

If I look at the UIFont definition, the properties are seems defined like regular properties (or at least this is what Xcode shows:

open class UIFont : NSObject, NSCopying, NSSecureCoding {
//...
    open var familyName: String { get }
    open var fontName: String { get }
    // etc

The type of the class is UICTFont though, not sure if it matters.

I would like to understand why this is not working, but my main question is more generic: is there any way to obtain the properties of the UIKit class (e.g. UIFont)?





samedi 21 mai 2022

ubuntu NAT Reflection for local server when deploying react app

All the static resources are displaying well with other PC, However all the static resources are not loading in the deployment Server itself

How can I set NAT Reflection or NAT loopback rules in iptables for this case?

public ip : 112.xxx.xxx.xxx
Program A - : 192.168.0.114:7000 (Webpack dev server)
Program B - : 192.168.0.114:3000 (react server)

program A and B is running on a different port in the same server I would like to access Program A from Program B with IP 112.xxx.xxx.xxx:7000/dist/bundle.js

port forwarding is already set for port 7000





vendredi 20 mai 2022

Set a property name based on instance name in java

I have a class like this (which I am developing)-

public class Comp { private String name; }

It is used in some other classes(which will be used by others and not in my control), like this

Comp username; 
Comp password;

What I want is, to set the name of the Comp object automatically same as the name of the instance created. That is in my case, it should return like this -

username.getName() -> "username"
password.getName() -> "password"

I need to do this on my side(that is, in the Comp class). Is this possible to achieve ?





Manipulate annotated property values as the DTO hits the Spring controller?

Can you manipulate properties (e.g. set null ones to Hello world) annotated with a custom annotation as they are handed over to methods in your controller?

For example, let's assume we have a nested DTO:

public class MyDto {
  @MyAnnotation
  private String myProperty;

  private String unannotatedPropety;

  private InnerEntity innerEntity;

  // Getters and setters omitted for brevity
}

public class InnerEntity {
  
  @MyAnnotation
  private String anotherProperty;
  
  // Getters and setters omitted for brevity
}

@RestController(...)
public class MyController {
  
  @PostMapping(...)
  public Mono<ResponseEntity<MyResponse>> myRequestHandler(@RequestBody Mono<MyEntity> json) {
    // ..
  }
}

I initially thought a ConditionalGenericConverter could do the trick (its signature allows for null values to be converted, and it provides TypeDescriptors for its source and target properties, making introspection a breeze), but for controllers, Spring actually uses HttpMessageConverter for payloads (kudos), it seems, and I didn't want to reinvent the entire Jackson deserializer.

On the other hand, Spring + Hibernate Validator manage to introspect payloads and check all properties for specific annotations, so getting to annotated properties should be possible, I hope...

I could probably use AspectJ, but I want this to work in general, and not rely on the payload being of a specific type (like MyDto)... I'm basically hoping there exists a hook I can use, just like the converters API, that does the heavy lifting of reflection for me...

Is there an (easy) approach to do what I want to do?





jeudi 19 mai 2022

C# DoNET 5 link a library with Dynamic DLL

I face an issue when i try to use a function from a .NET C# library class link to another library class loaded by Reflection

Here the Application call :

       private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Call static
            var lib = new StaticLib.StaticClass();
            var a = lib.Test(1); // Works fine


            // Call dynamic
            var DLL = Assembly.LoadFile(Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + "DynamicLib.dll");

            var theType = DLL.GetType("DynamicLib.DynamicClass");
            var inst =  Activator.CreateInstance(theType);
            
            var method_1 = theType.GetMethod("GetInvert_1");
            var b = method_1.Invoke(inst, new object[] { 1 }); // Works fine
            
            var method_2 = theType.GetMethod("GetInvert_2");
            var c = method_2.Invoke(inst, new object[] { 1 }); // Exception
        }

The Dynamic library :

namespace DynamicLib
{
    public class DynamicClass
    {
        public static int GetInvert_1(int value)
        {
            return value * (-1);
        }

        public static int GetInvert_2(int value)
        {
            var lib = new StaticLib.StaticClass();
            return lib.Test(value);
        }
    }
}

The Static library used by the dynamic library :

namespace StaticLib
{
    public class StaticClass
    {
        public int Test(int value)
        {
            return value * (-1);
        }
    }
}
  • Tha call var lib = new StaticLib.StaticClass(); var a = lib.Test(1); : Works perfectly
  • The call var a = method_1.Invoke(c, new object[] { 1 }); works perfectly.
  • The call var b = method_2.Invoke(c, new object[] { 1 }); crashes at the right moment of Invoke. If i remove the call to StaticLibray.StaticClass.test, there is no problem.

Exception interne 1 : FileNotFoundException : Could not load file or assembly 'StaticLib, Version=1.0.0.0, >Culture=neutral, PublicKeyToken=null'. Le fichier spécifié est introuvable.

It makes me confused, because through the Dynamic library, i can not call the function Test. The file StaticLib.dll is in the same directory than the other files. If i remove the file StaticLib.dll, i can even not start the application. So the problem comes to the link between DynamicLib.dll and StaticLink.Dll

thank for help





How to get attributes of annotations in Java using reflection?

I have several data classes in java of which I want to know - using reflection - which fields have a certain annotation with a certain attribute which is the following:

@Column(columnDefinition = "text") // Text with unbound length
private String comment;

I figured how to get the annotations of the field and whether it is of type Column:

private boolean isStringFieldWithBoundLength(Field attr) {
    Annotation[] annotations = attr.getDeclaredAnnotations();
    for (Annotation ann : annotations) {
        Class<? extends Annotation> aClass = ann.annotationType();
        if (Column.class == aClass) {
            
            // ...
            
        }
    }
}

Now in the debugger I can see that the aClass object has the information about the provided parameters. Unfortunately I don't know how to access it with code. Is it possible to access this information in java?





Is there a (portable) way to detect layout change in C++ classes?

For example say I have a class Foo with a typical serialization pattern.

struct Foo {
    int a;
    bool b;
    template <typename Archive>
    void serialize(Archive & ar) {
        ar & a;
        ar & b;
    }
};

Now suppose somebody comes along and adds a field.

struct Foo {
    int a;
    bool b;
    std::string c;

    template <typename Archive>
    void serialize(Archive & ar) {
        ar & a;
        ar & b;
    }
};

This compiles just fine but the Archive method is wrong. I could add something like


namespace detail {
template <int a, int b>
void AssertSizeOfImplementation() {
    static_assert(a == b, "Size does not match (check stack trace)");
}
}  
template <typename T, int size>
void AssertSizeOf() {
    detail::AssertSizeOfImplementation<sizeof(T), size>();
}


struct Foo {
    int a;
    bool b;

    template <typename Archive>
    void serialize(Archive& ar) {
        ar& a;
        ar& b;
        AssertSizeOf<Foo,8>();
    }
};

and now if I add the extra field I will see a compile error

: In instantiation of 'void detail::AssertSizeOfImplementation() [with int a = 40; int b = 8]':

I can then fix my serialization code and update the assertion.

However this is not very portable. sizeof will return different results depending on packing and architecture.

Are there any other alternatives to using sizeof?

( play with this on godbolt https://godbolt.org/z/fMo8ETjnr )





mardi 17 mai 2022

Non-reflective way to set properties of a type known at compile time

I am working on a project that requires a user to be able to modify properties of an object within a certain list of types, known at compile time.

For example, say I have a type defined by

public class A
{
   public float foo;
}

To set properties without reflection at near-native speeds during runtime (which is necessary for the project), I used a C# script which enumerates through the properties using reflection to generate code that looks something like this, which is then compiled.

public void Set(A obj, string path, object value)
{
    switch (path)
    {
        case "foo":
            obj.foo = (float)value;
            break;
    }
}

This works fine for simple types, but for more complex types, specifically where struct properties are its members, it becomes more difficult.

public class B
{
    public C foo { get; set; }
}
public struct C
{
    public float bar;
}

The code generated by this system no longer works, because accessing the struct property creates a copy.

public void Set(B obj, string path, object value)
{
    switch (path)
    {
        //...
        case "foo.bar":
            // Cannot modify the return value of 'C.bar' because it is not a variable
            obj.foo.bar = (float)value;
            break;
    }
}

Now, what I can do is modify the system to create a temporary struct variable, modify the member I want to access, and set the property's value to the temp variable, like so.

public void Set(B obj, string path, object value)
{
    switch (path)
    {
        //...
        case "foo.bar":
            C tmp = obj.foo;
            tmp.bar = (float)value;
            obj.foo = tmp;
            break;
    }
}

This system has several problems though. Nested struct properties would be hell to unwrap, and I would have to check every single parent property to ensure a setter method exists. This seems unnecessary and cumbersome, but I don't see any other option.

Is there a way that I can set property values for an object from a string path without runtime reflection?





FieldInfo.SetValue(): Object of type 'System.String' cannot be converted to type 'System.Int32'

Program Logic:

  • Define some default values for an Employee in the C# program
  • Read an XML file about different Employees
  • Use Reflections to go through all the fields of the DefaultAttributes class
  • If a field name is present as an attribute in an Employee's XML node then, override the default value with the attribute value

Employee DefaultAttributes Class

public class DefaultAttributes
{
    public string EmployeeName = "XYZ";
    public int[] ProjectCodes = new int[] { 1, 1 };
    public string city = "Munich";
}

XML File:

   <TopNode Id="A">
      <MiddleNode EmployeeName="John">
         <InnerMostNode Age="46" Average="88.15" ProjectCodes="46 112" City="Berlin">            
         </InnerMostNode>
      </MiddleNode>
      <MiddleNode EmployeeName="Claudia">
         <InnerMostNode Age="50" Average="96.58" ProjectCodes="9 510">            
         </InnerMostNode>
      </MiddleNode>
   </TopNode>

Use of Reflections To Override Default Values:

    private void OverrideAttribites(XmlNode xmlNode, DefaultAttributes nodeAttributes)
    {
        //Traverse through all fileds of DefaultAttributes class
        FieldInfo[] fieldsOfDefaultAttributesclass = typeof(DefaultAttributes).GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (var field in fieldsOfDefaultAttributesclass)
        {
            // Check if the "field" is present in the attributes of the current XML node
            string fieldName = field.Name;
            if (xmlNode.Attributes[fieldName] is not null) //i.e. field is present in the Attributes list
            {
                var attValue = xmlNode.Attributes[fieldName].Value;

                if (attValue.Contains(' ')) //i.e. attribute value should be stored in an array type
                {
                    if (!fieldName.Contains('['))
                    {
                        throw new Exception("Field type is not an array type but the XML attribute value contains an array");
                    }

                    //Set Array Value
                }
                else
                {
                    //PROBLEM: THIS LINE THROWS EXCEPTION !!!!!
                    field.SetValue(nodeAttributes, xmlNode.Attributes[fieldName].Value);
                }
            }
        }
    }

Question: The attributes values in my XML file are present string format. How do I use the attribute's value to set a field's value in a generic way (field could be int, double, int[] etc.)?





dimanche 15 mai 2022

Pass enum 'field' via reflection in Kotlin

In Kotlin, it's easy to pass a property as a KProperty or KProperty1 like this for example:

inline fun <TRet, reified TOwner> getName(property: KProperty1<TOwner, TRet>): String {
    return "${TOwner::class.simpleName}.${property.name}"
}

And then given the following type:

class Example(val exampleName: String)

I could call getName(Example::exampleName) which would return Example.exampleName.

Is there any way to do this with enums?

Say I had the following enum class:

enum class ExampleEnum { VALUE1, VALUE2 }

Is there any way to get ExampleEnum::VALUE1 or some useful reflection object about the values in ExampleEnum? I essentially want to be able to access the declaring KClass (or java class) and the field being accessed in the enum, just by passing one argument.

The alternative is to write something like getName(ExampleEnum::class, "VALUE1") which is verbose and doesn't play well with refactorings/renames. Also, please note the getName is just an example, the actual use case is a bit more general.





samedi 14 mai 2022

Field.set does not update the value

I have assigned an annotation to my field, namely SubDocument. Saving and loading is not a problem.

Under the method read() I say dataSetting.currentValue(value); This all works and also the variable value has the correct value. This is followed by the call field.set(classObject, dataSetting). The variable dataSetting should now update the field.

Debug results:

As you can see, the variable value contains the value "Übersicht2" and it is set successfully. When debugging field.set(classObject, dataSetting), you can also see that the currentValue=Übersicht2

Now the problem is that if I call the field via the variable and call the method #getCurrentValue, I still get back null.

Thank you for any help.

Field:

    @SubDocument(save = "master_inventory_title", read = "master_inventory_title")
    private final DataSetting<String> title = new DataSetting<String>().builder()
            .defaultValue("Übersicht")
            .build();

How I update:

    private void initSubDocuments() {
        for (Class<?> clazz : reflections.getTypesAnnotatedWith(Document.class)) {
            YamlConfiguration config = getConfig(clazz);
            if (config == null) continue;

            for (Field field : clazz.getDeclaredFields()) {
                SubDocument subDocument = field.getAnnotation(SubDocument.class);
                if (subDocument == null) continue;

                try {
                    Constructor<?> constructor = getEmptyConstructor(clazz);
                    if (constructor == null) continue;

                    Object classObject = constructor.newInstance();
                    boolean isAccessible = field.canAccess(classObject);

                    field.setAccessible(true);

                    Object dataObject = field.get(classObject);

                    if (dataObject instanceof Setting<?>)
                        loadSetting((Setting<?>) dataObject, clazz, classObject, field, subDocument, config);

                    if (dataObject instanceof OptionSetting<?>)
                        loadOptionSetting((OptionSetting<?>) dataObject, clazz, classObject, field, subDocument, config);

                    if (dataObject instanceof DataSetting<?>) {
                        loadDataSetting((DataSetting<?>) dataObject, clazz, classObject, field, subDocument, config);

                    }


                    field.setAccessible(isAccessible);
                } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }

                this.subDocuments.add(subDocument);
            }
        }
    }
    private void loadDataSetting(@NotNull DataSetting<?> dataSetting, @NotNull Class<?> clazz, @NotNull Object classObject, @NotNull Field field, @NotNull SubDocument subDocument, @NotNull YamlConfiguration config) throws IllegalAccessException {
        save(subDocument, config, clazz, dataSetting.getDefaultValue());
        read(null, null, dataSetting, field, subDocument, classObject, config.get(subDocument.read()));
    }

    private <T> void save(@NotNull SubDocument subDocument, @NotNull YamlConfiguration config, @NotNull Class<?> clazz, @NotNull T defaultValue) {
        if (!subDocument.save().equals("unknown") && !config.isSet(subDocument.save())) {
            config.set(subDocument.save(), defaultValue);
            saveConfig(clazz);
        }
    }

    private void read(@Nullable Setting<?> setting, @Nullable OptionSetting<?> optionSetting, @Nullable DataSetting<?> dataSetting, Field field, SubDocument subDocument, Object classObject, Object value) throws IllegalAccessException {
        if (setting != null && !subDocument.read().equals("unknown")) {
            setting.currentValue(value);
            field.set(classObject, setting);
            return;
        }
        if (optionSetting != null && !subDocument.read().equals("unknown")) {
            optionSetting.currentValue(value);
            field.set(classObject, optionSetting);
            return;
        }
        if (dataSetting != null && !subDocument.read().equals("unknown")) {
            dataSetting.currentValue(value);
            field.set(classObject, dataSetting);
        }
    }





Load Assembly compiled with newer .Net Framework than executing assembly

I have an application compiled with .Net Framework 4.0 and I want to load a WPF UserControl inside it. The user control is a dll compiled for .NetFramework 4.8.

I have been doing some tests with Console Application and I have loaded from .NetFramework 4.0 a dll using reflection. The dll is compiled with .NetFramework 4.8 and using for example the RSA constructor introduced in .NetFramework 4.7

using (var rsa = RSA.Create(2048)){}

It seems that everything is working well. Is this permited or maybe I will have some problem? I thougth that this will fail due the executing or calling assembly was compiled in .Net Framework 4.0.





Create program that read the xml and create Java Objects from it. (something like Spring application context)

Hi there as I mentioned in title I want create program which read xml and create beans(Objects) from it.

 <beans>
    <bean id="person3" class="Person">
    <property name="id" value="3"/>
    <property name="firstname" value="Jhone"/>
    <property name="lastname" value="Smith"/>
    <property name="email" value="jhone.smith@gmail.com"/>
    <property name="age" value="31"/>
</bean>

I read the nodes and their attributes and put them in the map. the problem is creating instances of that beans. here is the method

public Object createInstance(String className, LinkedHashMap<String,Object> attributes){
    Class<?> tt = Class.forName(className);
    Field[] declaredFields = tt.getDeclaredFields();
    Class<?>[] types = Arrays.stream(declaredFields).map(Field::getType).toArray(Class<?> []::new);
    Object[] values = attributes.values().toArray();
    Object[] valuesMatch = new Object[types.length];

    Constructor<?> constructor =  tt.getConstructor(types);
    constructor.newInstance(values);  //throws Exception

so I got values, and types of that values. values are All of String type. the question is , is there any way to create an instance of Object by its type and String value? I need something like this

Object (Class class, String value){
the class type is Integer,
so String value will be parse to int
Integer i = Integer.valueOf(value)
return i;}




vendredi 13 mai 2022

ByteBuddy Agent to print method elapsed time

I'm trying to measure the time for certains method of some specific classes. I'm using ByteBuddy and I created the following interceptor class:

public class TimingInterceptor {
    @RuntimeType
    public static Object intercept(@Origin Method method,
                                   @SuperCall Callable<?> callable) {
        long start = System.currentTimeMillis();
        try {
            return callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(method + " took " + (System.currentTimeMillis() - start));
        }
        return null;
    }
}

And this is the Java Agent Class I'm using:

public class TimerAgent {
    public static void premain(String arguments,
                               Instrumentation instrumentation) {

        new AgentBuilder.Default()
                .type(ElementMatchers.nameStartsWith("BP")) // This is because I used the prefix BP to name methods I need to measure
                .transform((builder, type, classLoader, module) ->
                        builder.method(ElementMatchers.any())
                                .intercept(MethodDelegation.to(TimingInterceptor.class))
                ).installOn(instrumentation);
    }
}

I ran a test application including methods named with "BP" as prefix, and the message in the class TimingInterceptor indicating the method duration is not shown.

Some ideas guys?

Example full code:





jeudi 12 mai 2022

Is it possible to set private static final field using Reflection in JDK 17 [duplicate]

I am trying to upgrade my application Java version from v1.8 to v17. There are some unit tests which are using Reflection to set value of private, static, final fields. I tried using VarHandle but no luck.





Get children method's annotation in Java using reflection or something like this

OBS: My code is java 8.
For example, I have this stacktrace:

MainClass:MethodA() calls
--------ClassB:MethodB() calls
------------ClassC:MethodC() @Cacheable calls
----------------ClassFinal:MethodD()

MethodA() -> MethodB() -> MethodC() -> MethodD();


In my example, ClassC:methodC() it's noted with @Cacheable. I need get this annotation in ClassFinal:MethodD(), something like this:

    public void MethodD() {
        Cacheable cacheable = ...
    }

I already done this using reflection, but it isn't work with overload:

    public static <T extends Annotation> T getStacktraceAnnotation(Class<T> type) {
        int currStack = 0;
        T result = null;
        
        //
        //
        StackTraceElement[] stackTraceElementArray = Thread.currentThread().getStackTrace();
        
        //
        //
        for (java.lang.StackTraceElement curr : stackTraceElementArray) {
            try {
                Method[] methods = Class.forName(curr.getClassName()).getMethods();
                
                for (Method currMethod : methods) 
                    if (currMethod.getName().equals(curr.getMethodName())) {
                        result = currMethod.getAnnotation(type);
                        if (result != null) break;
                    }
                //
                //
                if (result != null || currStack++ > 6) break;
            } catch(Exception exc) {
                // Nothing!
            }
        }
        //
        //
        return result;
    }

Real stacktace of my program:

fff.commons.serverless.abstracts.v2.AbstractCommonIntegrationHttp.sendGet(AbstractCommonIntegrationHttp.java:320) 
fff.commons.serverless.abstracts.v2.Teste.a(Teste.java:14) 
fff.commons.serverless.abstracts.v2.Teste.main(Teste.java:18)

Teste.a(Teste.java:14) is noted with @Cachable
And I need get this anottation in sendGet(AbstractCommonIntegrationHttp.java:320)

My annotation:

@Retention(RUNTIME)
@Target({ TYPE, METHOD })
@Inherited
public @interface Cacheable {
    int secs() default 15;
}




mercredi 11 mai 2022

Cannot get method by reflect when defining a new type from an existing type

I use type declarations to custom type within gorm, the following code works fine:

type LocalTime time.Time

func (t LocalTime) MarshalJSON() ([]byte, error) {
    pt := time.Time(t)
    return []byte(fmt.Sprintf("\"%s\"", pt.Format("2006-01-02 15:04:05"))), nil
}
// ...etc

When I need to further more work with gocsv, matters come.

func (t *LocalTime) MarshalCSV() (string, error) {
    s, err := t.MarshalJSON()
    return string(s), err
}

type APIInfo struct {
    ID            uint64         `gorm:"type:bigint unsigned AUTO_INCREMENT;primaryKey;column:id" json:"-" csv:"-"`
    AccessTime    LocalTime      `gorm:"column:access_time" json:"access_time" csv:"access_time"`      
}

var infos []*APIInfo
// ...
gocsv.MarshalBytes(infos)

gocsv use reflect to detect whether a custom type has MarshalCSV method like below

reflect.TypeOf(localTime).MethodByName("MarshalCSV")

In this case, reflect.TypeOf(localTime) will return type of time.Time, which doesn't have MarshalCSV.

How can I fix it with as little damage to the existing code as possible?





lundi 9 mai 2022

C# Reflection Invalid Cast Exception

I am getting the following error from the C# code below.

public static PropertyInfo GetPropertyInfo<T, T2>(this Expression<Func<T, T2>> propertyLambda)
{
    var member = propertyLambda.Body as MemberExpression
        ?? ((UnaryExpression)propertyLambda.Body).Operand as MemberExpression;    
}

System.InvalidCastException : Unable to cast object of type 'System.Linq.Expressions.MethodCallExpressionN' to type 'System.Linq.Expressions.UnaryExpression'

Attached is the front end code in MVC which gets called to this C# code

.AddControl(x => x.SipKpiCriteria.Select(y => y.EvaluationMethod).FirstOrDefault())




dimanche 8 mai 2022

Delegate.CreateDelegate(Type, object, MethodInfo) throws ArgumentException "Cannot bind to the target method..."

I use a serializer "NetStack.BitBuffer". With reflection I get all read methods like Int32 ReadInt, UInt32 ReadUInt etc.

To speed up the invoke from the methodinfo I create delegates but suddently after next time I wanted to work and even was recording it to make vlog but same code shows exception. I debugged it and all values are correct but still it is not working.

public class BitBuffer // Recreated to test it
{
    public int ReadInt()
    {
        return 1;
    }
}

[Test]
public void DelegateCreateTest()
{
    BitBuffer bitBuffer = new BitBuffer();

    MethodInfo readIntMethod = bitBuffer.GetType().GetMethod("ReadInt");

    Assert.IsNotNull(readIntMethod, "Should not be null");

    var func = (Func<object>)Delegate.CreateDelegate(typeof(Func<object>), bitBuffer, readIntMethod);

    Assert.IsNotNull(func, "Should not be null");
}

The test code above worked before the exception started to show.

System.ArgumentException: 'Cannot bind to the target method because its signature is not compatible with that of the delegate type.'

If change my self to Func<int> then it works but you could guess it.. all other methods with other return type will not work.

If I google it actually shouldn't even possible to do this except post: The identical code which I found was here and seems like it should actually work: https://stackoverflow.com/a/44595323/5103256

I really get crazy like error in the matrix and cannot explain why suddently it is not working. Tooooo bad I didn't use git to follow what is different.





samedi 7 mai 2022

Mapping profile instance doesn't creates

I'm trying to add automapping models with reflection, I created an interface IMapFrom<> and implemented it in all dtos. Then I created class

public class MappingProfile : Profile
{
    public MappingProfile(Assembly assembly)
        => ApplyMappingsFromAssembly(assembly);

    private void ApplyMappingsFromAssembly(Assembly assembly)
    {
        var types = assembly
            .GetExportedTypes()
            .Where(t => t
                .GetInterfaces()
                .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>)))
            .ToList();

        foreach (var type in types)
        {
            var instance = Activator.CreateInstance(type);

            const string mappingMethodName = "Mapping";

            var methodInfo = type.GetMethod(mappingMethodName)
                             ?? type.GetInterface("IMapFrom`1")?.GetMethod(mappingMethodName);

            methodInfo?.Invoke(instance, new object[] { this });
        }
    }
}

And add it in service collection

public static IServiceCollection AddAutoMapperProfile(IServiceCollection services, Assembly assembly)
         => services
             .AddAutoMapper(
                 (_, config) => config
                     .AddProfile(new MappingProfile(Assembly.GetCallingAssembly())),
                 Array.Empty<Assembly>());

Why the class instance is not created? Because of this I can't convert the model into a dto





Iterate over the fields of an object

I have a singleton objet with 100 different case classes. For example:

object Foo {

case class Bar1 {
...
}

... 

case class Bar100 {
...
}
}

I would like to be able to iterate over each of the case class. Something like getting all the case classes in a Seq and then being able to map over it. (map with a polymorphic function for example)

Is it possible using reflection? If yes how? And what are the drawbacks of using reflection here over hard coding a sequence with all the case classes.





vendredi 6 mai 2022

Mask from bitfield in C++

Here's a little puzzle I couldn't find a good answer for:

Given a struct with bitfields, such as

struct A {
    unsigned foo:13;
    unsigned bar:19;
};

Is there a (portable) way in C++ to get the correct mask for one of the bitfields, preferably as a compile-time constant function or template?

Something like this:

constinit unsigned mask = getmask<A::bar>();  // mask should be 0xFFFFE000

In theory, at runtime, I could crudely do:

unsigned getmask_bar() {
    union AA {
        unsigned mask;
        A fields;
    } aa{};
    aa.fields.bar -= 1;
    return aa.mask;
}

That could even be wrapped in a macro (yuck!) to make it "generic".

But I guess you can readily see the various deficiencies of this method.

Is there a nicer, generic C++ way of doing it? Or even a not-so-nice way? Is there something useful coming up for the next C++ standard(s)? Reflection?





jeudi 5 mai 2022

Using reflection to identify if the error thrown matches expected error

I need to write a simple code tester program, but I got stuck comparing the given error class with the test expected class. I am supposed to use reflection in this exercise.

I have my code testing class:

public class TestRunner {

    private String result = "";

    public void runTests(List<String> testClassNames) {
        for (String testClassName : testClassNames) {
            Class<?> clazz;
            try {
                clazz = Class.forName(testClassName);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("No such class.");
            }
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (method.getAnnotation(MyTest.class) != null) {
                    if (testClassName.equals("reflection.tester.ExampleTests1")) {
                        result += method.getName() + "() - ";
                        ExampleTests1 instance = new ExampleTests1();
                        try {
                            // if null, result = OK
                            method.invoke(instance);
                            result += "OK\n";
                        } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
                            // if error is caught result = FAILED
                            result += "FAILED\n";
                        }
                    } else {
                        // the second class. should only return "OK" if the error is implemented from the exception class
                        result += method.getName() + "() - ";
                        ExampleTests2 instance = new ExampleTests2();
                        try {
                            method.invoke(instance);
                            result += "FAILED\n";
                        } catch (RuntimeException e) {
                            Throwable original = e.getCause();
                            Object expected = method.getReturnType();
                            if (original.getClass().isAssignableFrom(expected.getClass())) {
                                result += "OK\n";
                            } else {
                                result += "FAILED\n";
                            }
                        } catch (InvocationTargetException | IllegalAccessException e) {
                            result += "ERROR\n";
                        }
                    }
                }
            }
        }
    }
}

Also have two test classes. In the first one there is only one rule, if the test won't throw an exception the test should pass, and it is working. The second class is more complicated. If the thrown error class is implemented or same to the expected error class then the test should pass and OK should be added to the result. Currently my code won't catch RunTimeException at all and moves to the last catch block. How can I fix this?

I will also add the test class for more information.

public class ExampleTests2 {

    @MyTest(expected = RuntimeException.class)
    public void test3() {
        throw new IllegalStateException();
    }

    @MyTest(expected = IllegalStateException.class)
    public void test4() {
        throw new RuntimeException();
    }

    @MyTest(expected = IllegalStateException.class)
    public void test5() {
        throw new IllegalStateException();
    }

    @MyTest(expected = IllegalStateException.class)
    public void test6() {
    }

    public void helperMethod() {
    }


}

test3() and test5() should pass, test4() and test6() should fail, helperMethod() won't be checked because I only need to use the tests with @MyTest annotation.





mercredi 4 mai 2022

How to register services with dependency container services by reflection in c#

I have an interface IProcessor and multiple processors implementing this interface:

Processor1 : IProcessor
Processor2 : IProcessor

I want to inject these processors into a class like: IEnumerable<IProcessor> so that I can run them one by one.

I can register these one by one with the microsoft dependency injection container, but I want to do it by reflection so that a newly added processor is registered automatically.

var processorInterface = typeof(IProcessor);

var processors = Assembly.GetExecutingAssembly().GetTypes()
               .Where(t => processorInterface.IsAssignableFrom(t) && t.IsClass && 
               !t.IsAbstract && t.IsPublic);                  

foreach (var processor in processors)
{
    serviceCollection.AddScoped(processor);

    // Below line does not compile of course
    //serviceCollection.AddScoped<IProcessor, processor>());
}

But this doesn't work, I always get an empty list injected.





Reflection EF .NET Core to get objects from database [duplicate]

I have requirment to get the data from context object using reflection concept in EF .NET Core. For Ex:

_context.TblClaim.Take(5).ToArray() 

In the above line of code I Need to pass TblClaim using reflection, then I need to get the top 5 records, Please someone help me on this. Note: If you need any info please let me know.





mardi 3 mai 2022

Golang Converting from one channel to Another channel of unknown type

Convert from channel to channel of type that implements interface in GO

I am working on a problem that requires me to write a Go utility that can take a Go channel with a type that implements an interface and write to it. Right now if I know the type of the Go channel I can perform the writes to the channel without a problem. I make a new item of the appropriate type and send it on the channel.

The problem occurs when I try to generalize this to any channel that implements the interface needed to make the new item. If I can make a converter that converts from my internal type "logFile" to the given channel's type using the interface "hasLog" to "SetLog" ensuring the internal field "Log" of the logFile and the struct that is passed on the channel are identical, this problem would be solved. However, since I cannot convert between a channel logFile and a channel any, or a channel hasLog, I can't make and send to the channel that is passed in even after the new item is created to be sent. Since the channel sent is not a channel logFile, or a channel hasLog, but instead a channel of type that implements hasLog, we can't do the conversion.

currently it works something like what is below.

type hasLog interface {
    setLog([]*string)
    getLog() []*string
}

// logFile this is a struct we use to send the log information.
// this is used for channeling support.
type logFile struct {
    Log []*string `json:",omitempty"`
}

// getLog this returns the log as sent by the logFile.
// this is used for channeling support.
func (r logFile) GetLog() []*string {
    return r.Log
}

// setLog this will set the log of the logFile.
// this is used for channeling support.
func (r logFile) SetLog(log []*string) {
    r.Log = make([]*string, 3)
    r.Log[0] = log[0]
    r.Log[1] = log[1]
    r.Log[2] = log[2]
}

func sendChannelInfo(r RsvFile) {
    if hasChannel() {
        logChannelMutex.Lock()
        defer logChannelMutex.Unlock()
        logChannel[getGID()] <- r
    }
}

// logSingle logs a formatted message sent to the appropriate place
func logSingle(level Level, message string, values ...interface{}) {
    
    var r logFile
    r.Log = make([]*string, 3)
    var logs = make([]*string, 3)

//generate the logs

    r.SetLog(logs)

    sendChannelInfo(r)

}

// SetChannel lets us set up a pipe between a channel that receives our channeled messages and our logger.
func SetChannel(receiver interface{}) {
    GID := getGID()
    sender := ChannelHandle(receiver)
    if receiver != nil {
        logChannel[GID] = sender
        return
    }
}

func ChannelHandle(receiver interface{}) chan RsvFile {
    sender := make(chan RsvFile)
    go convertChannel(sender, receiver)
    return sender
}

func convertChannel[T any](sender <-chan RsvFile, receiver T) {
    for {
        item := <-sender
        channelType := reflect.ValueOf(receiver).Type().Elem()
        var new = reflect.New(channelType).Elem().Interface()
        log := item.GetLog()
        println(len(log))
        input := make([]reflect.Value, 1)
        input[0] = reflect.ValueOf(log)
        reflect.ValueOf(new).MethodByName("SetLog").Call(input)
        receiver <- new
    }
}

Is there a way to send to the channel provided by "SetChannel" by converting my internal type to the arbitrary other type so long as data structure implements "hasLog"?





How to convert class properties of single type to list of that type

Given the following class:

class MyClass {
    readonly MyType Object1 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    readonly MyType Object2 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    readonly MyType Object3 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    readonly MyType Object4 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    // etc, there are 100+ in this class, all of the type MyType
}

Is there a way I can turn this into a list of either the type MyType or the prop Prop1?

The class only contains properties of the type MyType.





lundi 2 mai 2022

How to change class primitive fields to respective wrapper fields dynamically?

I have a class from third party jar which have primitive fields inside it. For example:

public class A {

private int id;

private int score;

//Getter And Setters below
}

I have another class which have all fields of A class and have more fields as well and can be partially updated. For example

public class B {

private Integer id;

private Integer score;

private Integer age;

//Getter and Setters below
}

B class is in my project and can be modified. Partial update is allowed in B class for example

B b = new B();
b.setAge(32);

Now using ModelMapper class I am doing the mapping of both the classes.

A object = new ModelMapper().map(b, A.class);

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(object, JsonNode.class);

As A class have primitive data type fields hence after mapping those fields get initialized with default value.

Current Outcome Expected Outcome
{"id" : 0, "score" : 0 ,"age" 32} {"age": 32}

Is there a way using which we can convert the A class primitive data types to wrapper classes like int to Integer so that instead of default value it get initialized with NULL value and later on can be ignore in JSON converter?

Or is there any way using which we can achieve this using ModelMapper.





How to fetch and update data present in a field by knowing the fields name as a string?

I have a CustomerDetailsEntity with fields ticketNum, firstName, lastName, dob, address, etc. For a certain Ticket number, I received a String data specifying some field names for which data might be incorrect.

For example, for ticketNum = 123, I received a field checkFields = "firstName, address"; So I have to fetch data of firstName and address for ticketNum 123 from DB and be able to update it.

I tried to solve this using java reflection concept.

CustomerDetailsEntity customer = customerDetailsRepo.findByTicketNum(123);

Field[] fields = customer.getfields;

I am getting error saying getfields() is not a method. How do I solve this issue? Any corrections or suggestions are greatly appreciated.