dimanche 31 juillet 2022

IllegalArgumentException on passing Proxy object as constructor argument in Kotlin/JVM

I am trying to instantiate instances generically for a (de)serialization library I am building. This sometimes requires object stubs to be generated automatically (they are later replaced by real instances).

When trying to do so, I call the constructor as a KFunction, which works for classes that only take preexisting values or plain values like Int, Long ... for which I have predefined stubs. When I as the library provider don't know a type I need a stub for, I want to proxy that type and later inject the actual value (the latter works perfectly). However whenever I try to call the constructor with the proxy provided, the constructor call throws an IllegalArgumentException.

I debugged to DelegatingConstructorAccessorImpl.newInstance where I cannot go any further as things start to get native. I am pretty certain, that the arguments are in the right order and all, because if I replace the value with a real instance it works, however the proxy is not identified as the expected type.

My proxies are generated like this:

Proxy.newProxyInstance(
    ClassLoader.getSystemClassLoader(),
    type.jvmErasure.java.interfaces,
    InvocationHandler { proxy, method, args ->
        if (method.name == "getClass") {
            println("PROXY: #getClass was called on proxy of type $type.")
            return@InvocationHandler type.jvmErasure.java

        } else if (method.name == "toString" && method.parameters.isEmpty()
            && method.returnType == String::class.java
        ) {
            return@InvocationHandler "Proxy<$type>"

        } else if (method.name == "equals" && method.returnType == Boolean::class.java) {
            println("PROXY: #equals was called on proxy of type $type.")
            return@InvocationHandler proxy === args[0]

        } else {
            throw UnsupportedOperationException("This method should not have been called: $method")
        }
    }
)

In the beginning I thought my method calls failed, and I am still unsure, if this is not the case. However the debugging of the JVM does not stop on any invokation, which suggests to me, that I am doing something else wrong with the proxy.

How can I make the proxy fit the expected constructor argument?

My constructor call is made like this:

private fun <T> newInstanceCatching(
    className: String,
    calledConstructor: KFunction<T>,
    params: Map<KParameter, Any?>
): T = try {
    calledConstructor.callBy(params)
} catch (e: Exception) {
    val readableParams = params.map { "\n${it.key.name}: ${it.key.type} = ${it.value}" }
    println("Failed to instantiate: $className by $calledConstructor with parameters: $readableParams")
    throw e
}

As mentioned, this works for actual instances as constructor parameters, just not when at least one parameter is a proxy.





How to properly extend singleton class?

I have a singleton class from vendor

class vendorSingleton
{
    protected static $instance = null;
 
    public static function getInstance() {
        if (!static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    ... some internal logic and getters/setters ...  
}

I need to extend it. Problem here is that both child and a parent MUST share the same instance, because its state is changed during request and is important for application logic. Also, both child and parent ::getInstance will be called, because I can't update all places so that they use child class directly. Currently I came up with this implementation and it works

class childSingleton extends vendorSingleton
{
    /**
     * @return static
     */
    public static function getInstance()
    {
        $instance = new static();
        $instanceReflection = new ReflectionClass($instance);
        $parentInstanceReflection = new ReflectionClass(parent::getInstance());

        foreach ($parentInstanceReflection->getProperties() as $parentProperty) {
            $parentProperty->setAccessible(true);

            $property = $instanceReflection->getProperty($parentProperty->getName());

            $property->setAccessible(true);
            $property->setValue($instance, $parentProperty->getValue(parent::getInstance()));
        }

        static::$instance = $instance;

        return static::$instance;
    }

    ... new method ...
}

But I don't really like it since it uses reflections and overall looks pretty error prone. Could this be done using other, better approach?





vendredi 29 juillet 2022

Create a hashmap with the names of the fields in the class as the key, and the values of those fields as the values of the map

Let's say you have a class: SomeClass with fields a=10, b=20, and c=30, where instanceOfSomeClass.getA()==10. I want a map like this

{
    a:10
    b:20
    c:30
}

I tried this, but got Class can not access a member of class with modifiers "private static final", but I also can't modify this class to not have private static final:

      Field[] fields = SomeClass.class.getDeclaredFields();
      for (Field f : fields) {
        map.put(f.toString(), f.get(instanceOfSomeClass).toString());
      }

Any ideas on how to make this hashmap?





Get specific overload method from Type.GetMethod() in C# [duplicate]

I am trying to get the MethodInfo for the method: EventCallBackFactory.Create<TValue>(Object, Action<TValue>) Documentation can be found here: EventCallBackFactory.Create

The code i am currently running however returns the version without a Type on the action ParameterEventCallBackFactory.Create<TValue>(Object, Action)

Here is my code:

MethodInfo? method = EventCallback.Factory.GetType().GetMethod("Create", 1, new Type[] { typeof(object), typeof(Action)});
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { PropertyType });

How can i Specify that i want the Overload version with Action<TValue> Parameter in the GetMethod() function?





Why can't I get the boolean value from nested classes property?

I am trying to use the GetValue() method of PropertyInfo, but it seems like its not working.

public bool IsDeviceOperable(ServiceType type, bool isServer, string domain)
{
    string settingsFileContent = _fileReader.Read(_filePathProvider.GetSettingsFilePath());

    var settings = _jsonDeserializer.Deserialize<Settings>(settingsFileContent);
    var settingsName = GetSettingsNameByType(type);

    string deviceType = GetDeviceType(isServer);

    var info = settings.GetType().GetProperty(domain.ToUpper())
        .PropertyType.GetProperty(settingsName)
        .PropertyType.GetProperty(deviceType);


    bool value = (bool)info.GetValue(settings, null);

    return value;
}

It throws System.Reflection.TargetException: 'Object does not match target type.'

My Settings file looks like this:

public class Settings
{
    public FirstDomain First { get; set; }
    public SecondDomain Second { get; set; }
    ...
}

Domain classes looks like this:

public class FirstDomain
{
    public Settings1 firstSettings { get; set; }
    public Settings2 secondSettings { get; set; }
    ...
}

public class SecondDomain
{
    public Settings1 firstSettings { get; set; }
    public Settings2 secondSettings { get; set; }
    ...
}

Settings classes look like this:

public class Settings1
{
    public bool RunOnClient { get; set; }
    public bool RunOnServer { get; set; }
}

public class Settings2
{
    public bool RunOnClient { get; set; }
    public bool RunOnServer { get; set; }
}

Please dont comment on the structure of the classes, it has to be this way. There is a reason for First Domain Second domain, and also the settings differ from each other, just for easier understanding, I renamed them.





Golang reflect get nil pointer underlying type

I would like to know if there is a way to "cast" a nil pointer of a struct into the (empty) struct itself using reflection or anything else.

My method parameters are an empty parent struct as an interface, a field name as a string and the field value as an interface.

The point is to get the real type of the field by going through the parent struct until I find the field matching the given name. I cannot just get the type of the value, because there will be cases where it won't return the correct type (for example a time.Time will be seen as a string).

The method can take any struct as parent, which is why it takes interfaces as parameters.

My problem is that the parent struct that is given is always a empty one (it serves only as a model), with default values. So fields that are pointers to substructs are nil. So to find the field given as parameter, I have to get the underlying substruct instead of the nil pointer to continue the search inside.

I cannot find a way to achieve that, I am not sure if that's even possible.

Any help is welcomed.





jeudi 28 juillet 2022

C# How to subscribe to an internal Action

How do I use reflection to subscribe, from a class, to a different class internal Action?

Such as

public class SneakyClass : Element
{
    internal Action<Trunk> OnConnect;
}
public class ResponderClass : Thing
{
    public SneakyClass OtherClass;

    public ResponderClass()
    {
        // doesn't work since the target is internal
        OtherClass.OnConnect += Callback;
    }

    public void Callback(Trunk t)
    {
        // do things
    }
}




Access Kotlin Interface/Class property by string key?

I need to access a class instance property similar to accessing a map in Kotlin.

For a map it goes like this

val myMap: Map<String, String> = mapOf("foo" to "bar")
assertThat(myMap["foo"]).isEqualTo("bar"

Now I want something similar to a class

data class House(
  val street: String
)

// pseudo code wish
fun foo() {
  val valueOfFoo: String = House::class.members["foo"].callGet()
}

I read into reflection but can't find a way to call it. I know the problem somewhat is that there is no class instance passed or specified. However I wonder if there is such thing?

val house = House("Baker Street 5")
val valueOfFoo: String = House::class.members["foo"].callGetWithInstance(house)
   
assertThat(valueOfFoo).isEqualTo("Baker Street 5")




mercredi 27 juillet 2022

Create a delegate from Methodinfo with generic parameter

Based on this old but very usefull article by the legendary Jon Skeet, I wrote a few methods to genereate Action Delegates from MethodInfos for faster invokations. But I ran into an issue, where I am unable to make any progress. See the example below:

public class DataContainer
{
    public List<int> myList;

    public DataContainer()
    {
        myList = new List<int>() { 1, 2, 3, 4 };
    }
}

public static class ExtensionMethods
{
    public static void DoStuff<T>(this IList<T> items)
    {
    }
}

public class Example
{
    private Action<object> doStuffQuickly;

    public void Test()
    {
        var fieldInfo = typeof(DataContainer).GetField("myList");

        var doStuffMethod = typeof(ExtensionMethods).GetMethod("DoStuff", BindingFlags.Public | BindingFlags.Static);
        var listType = typeof(IList<>).MakeGenericType(fieldInfo.FieldType.GenericTypeArguments);
        doStuffQuickly = QuickAccess.CreateWeakActionWithOneParam(doStuffMethod, listType);

        var data = new DataContainer();
        var list = fieldInfo.GetValue(data);

        doStuffQuickly(list);
    }
}

public static class QuickAccess
{
    private static MethodInfo _weak1ParamActionCreator;
    private static MethodInfo Weak1ParamActionCreator => _weak1ParamActionCreator
        ??= typeof(QuickAccess).GetMethod(nameof(CreateWeakExplicit1ParamAction), BindingFlags.Static | BindingFlags.NonPublic);

    public static Action<object> CreateWeakActionWithOneParam(MethodInfo methodInfo, Type paramType0 = null)
    {
        var parameters = methodInfo.GetParameters();
        paramType0 ??= parameters[0].ParameterType;
        var creationMethod = Weak1ParamActionCreator.MakeGenericMethod(paramType0);
        return (Action<object>)creationMethod.Invoke(null, new object[] { methodInfo });
    }

    private static Action<object> CreateWeakExplicit1ParamAction<TValue>(MethodInfo methodInfo)
    {
        var action = CreateStrongExplicit1ParamAction<TValue>(methodInfo);
        return (object value) => action((TValue)value);
    }

    private static Action<TValue> CreateStrongExplicit1ParamAction<TValue>(MethodInfo methodInfo)
    {
        //Debug.Log(methodInfo.GetParameters()[0].ParameterType.Name + " <-> " + typeof(TValue).Name);
        //Debug.Log(PrintTypes(methodInfo.GetParameters()[0].ParameterType.GenericTypeArguments) + " <-> "
        //    + PrintTypes(typeof(TValue).GenericTypeArguments));
        return (Action<TValue>)Delegate.CreateDelegate(typeof(Action<TValue>), methodInfo);
    }

    private static string PrintTypes(Type[] types)
    {
        return string.Join(", ", types.Select(t => t.Name));
    }
}

This fails with ArgumentException: method arguments are incompatible when trying to create the delegate. The commented logs print IList`1 <-> IList`1 and T <-> Int32, which made me think that maybe

var listType = typeof(IList<>).MakeGenericType(fieldInfo.FieldType.GenericTypeArguments);

should instead simply be

var listType = typeof(IList<>);

but that is causing an InvalidOperationException: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

I don't know how to proceed from here. Any help will be appreciated.





java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType using Coroutines Suspend function

I'm trying to setup a mechanism for retrofit in order to fetch data from both local jsons and remote API.

@Provides
@LoginScope
open fun providesLoginService(retrofitAPI: RetrofitAPI) : LoginService {
    return retrofitAPI.createService<LoginService>(LoginService::class.java)
}

For remote API, everything works fine. For local JSONs files I am using a proxy:

 private fun <Service> createServiceDemo(mClass: Class<Service>): Service {
    return Proxy.newProxyInstance(
        mClass.classLoader,
        arrayOf(mClass),
        DemoInvocationHandler(mContext)
    ) as Service
}

fun <Service> createService(mClass: Class<Service>) : Service {

    val service = if (abSession.isDemoMode() == true) {
        createServiceDemo(mClass)
    } else {
        retrofit.create(mClass)
    }

    return service
}

This is the Invocation Handler class where I have the problem:

class DemoInvocationHandler(val context: Context) : InvocationHandler {
@Throws(Throwable::class)
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any {

    val returnType = method?.genericReturnType
    
    val parameterizedType = returnType as ParameterizedType
    val _classResponse = TypeToken.get(parameterizedType.actualTypeArguments[0]).type
    val demo = method?.getAnnotation(Demo::class.java)
    return CallFromJSON<Any?>(context, demo?.demoFile ?: "", _classResponse)
}

}

method?.genericReturnType always returns an Object instead of returning the Generic Type.

This is the thrown message: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

Once I remove the suspend keyword from loginOld method, the cast is working.

I guess I have a problem with reflection combined with coroutines.

Any help ? Thanks in advance.





mardi 26 juillet 2022

How to read a RepeatedField (or at least its lenght) using Google.Protobuf.Reflection?

I am writing tests for a C# application supporting several Protobuf definitions of the same objects... which are unfortunately not very compatible to each other.

So I have written the following utility methods using Google.Protobuf.Reflection:

namespace ProtobufUtils
{
    using Google.Protobuf;
    using Google.Protobuf.Collections;
    using Google.Protobuf.Reflection;
    ...

    public static uint ReadUint(this IMessage msg, string fieldName)
    {
        FieldDescriptor field = msg.Descriptor.FindFieldByName(fieldName);
        return (uint)field.Accessor.GetValue(msg);
    }

    public static string ReadString(this IMessage msg, string fieldName)
    {
        FieldDescriptor field = msg.Descriptor.FindFieldByName(fieldName);
        return (string)field.Accessor.GetValue(msg);
    }

Using the above methods I am able to read out some common fields from IMessage objects in my tests:

    [DataTestMethod]
    [DynamicData(nameof(GetAllVersionsToTest), typeof(BaseUnitTest), DynamicDataSourceType.Method)]
    public async Task GetConfigurationShouldContainSessionToken(uint version)
    {
        IMessage cfgReq = ProtobufUtils.GenerateConfigRequest(version);

        uint reqVersion = ProtobufUtils.ReadUint(cfgReq, "version");
        string reqId = ProtobufUtils.ReadString(cfgReq, "id");
        string reqEtag = ProtobufUtils.ReadString(cfgReq, "etag");

My question is:

Sometimes I also need to assert, that a RepeatedField has no elements.

How to do it please, by using reflection?

For example, in the .proto file I have:

message ConfigurationResponse {
    uint32 version = 1;
    string id= 2;
    string etag = 3;
    repeated ContainerConfiguration configuration = 4;
    reserved 5, 6;
}

How can I read out the ContainerConfiguration field using reflection and verify, that it is empty?

(and I do have to use reflection, because there are 4 not very compatible versions of ContainerConfiguration to be supported by our application... and more are coming).





in C#, check for Null or Empty Properties in one object and Populate from another object

I have three different objects of same class with some properties missing in one whereas available in other. Now, I want to write a function which if finds empty or null property in one object, gets data for the same property from second object and so on up to three different objects. I want to write a generic method since there are multiple classes where I need to implement it. The return type should have all the properties with values populated from any of the three objects where these are not empty.

Any suggestions would be appreciated.





How to auto load/ import model, serializer as per the conditional requirement in any view using Django

I am in need of an Auto Import for Custom Model and Serializer Accordingly as per the condition, in any view.

Problem Case: Here I created two Classes(VIEWS) in Django one is specifically taking requests and another is the Base class that will control all the requests using the (get_data()) function and returns the valid data and response.

SampleView.py:

from .src.views.BaseRequestClass import BaseRequestClass

class SampleView(APIView):
    def get(self, request):
        d = BaseRequestClass
        model = request.query_params.get('model') # Model name I am getting in Request
        data = d.get_data(model)
        return Response(data, status=status.HTTP_200_OK)

BaseClass.py:

class BaseRequestClass:
    def get_data(models):
        dictionary = {"stu": ['StudentModel', 'StudentSerializer']}
        if models =='stu':
            model = # here auto-import of the model required as per above dictionary only if condition matched else no import will take place for this model
            serializer = # here auto-import of the serializer required as per above dictionary only if condition matched else no import will take place for this model
        
        details = model.objects.all()
        serial = serializer(details, many=True).data
        return serial

Where is the mistake or issue while writing this and what code can help me to import in it that I don't have to import all together, just as per condition only those custom Models and Serializers get Import?

I hope this question will be understood if there is any doubt please let me know.





lundi 25 juillet 2022

Assign an interface to an interface struct field in Golang

Consider we have an aggregation struct of interfaces

type Aggregation struct {
    a InterfaceA
    b InterfaceB
    ...
    n InterfaceN
}

we are trying to make the following function to initialize this struct's fields more funky -- to eliminate the switch:

func (a *Aggregation) Register(i interface{}) *Aggregation {
    switch v := i.(type) {
    case InterfaceA:
        a.a = v
    case InterfaceB:
        a.a = b
    ...
    case InterfaceN:
        a.a = v
    }
    return a
}

is there any way to accomplish the same functionality with reflection?





dimanche 24 juillet 2022

gRPC create stub from reflection server

If I have a grpc server running that is exposing the reflection service, is there some way to connect to it and generate the stub in some language to call it?

Like using protoc but referencing the server instead of the .proto files





samedi 23 juillet 2022

Accessing Struct Constructor Values or Creating new Struct Properties at Runtme

I am using BepInEx, which is a derivative of Harmony, to patch a game's assembly at runtime.

The original struct I want to modify looks like this:

public struct OriginalStruct
{
    
    public OriginalStruct(SomeClass someClass)
    {
        this.Property = someClass.SomeClassProperty1;
    }

    public float Property;

I am able to modify the constructor itself, and add variables that access properties from SomeClass. However, I need to create public properties of these new variables in other for other patched methods in external classes I have modified to be able to access them via these new properties.

The patched struct will look like this:

public struct OriginalStruct
{
    
    public OriginalStruct(SomeClass someClass)
    {
        this.Property = someClass.SomeClassProperty1;
        this.MyProperty= someClass.SomeClassProperty2;

    }

    public float Property;

    public float MyProperty;

The original method that accesses OriginalStruct looks like this:

public void SomeOriginalMethod(ref OriginalStuct originalStuct)
{
 float someVariable = originalStruct.Property
}

I want to patch it to look like this:

public void PatchedSomeOriginalMethod(ref OriginalStuct originalStuct)
{
 float someVariable = originalStruct.Property
 float myVariable = originalStruct.MyProperty
}

So the issue is finding some way of accessing struct constructor values directly, or accessing its instance of SomeClass so that I can access its property from within SomeOriginalMethod.

The only alternative I see is to add properties to OriginalStuct.

My understanding is that this is beyond the limits of runtime patching with the CIL. I've seen suggestions of subclassing the original class/struct via System.Reflection.Emit but I haven't found any good, understandable examples that does what I'm trying to do here specifically. I'm open to any ideas on how to achieve this, and I'm looking for solid example code.





vendredi 22 juillet 2022

Can my C# code tell if it's running a decompiled version of itself?

Is there any check or test that I can add to my code to determine if it's running the original version or a decompiled version?





jeudi 21 juillet 2022

Can't find constructors of Kotlin class

class Foo(context: Context) { ... }
class Bar(context: Context): Foo(context) { ... }

When I try to construct a Bar like:

Bar::class.java.getConstructor(Context::class.java).newInstance(context)

I get NoSuchMethodError. If I look at Bar::class.java.constructors the result is empty. What am I missing?





Reading properties of hierarchical classes and fill them to Treeview in C#

I have a set of classes like below:

public class Shipment : EntityBase
{
    [DataMember]
    public Address Sender { get; set; }

    [DataMember]
    public Address Receiver { get; set; }

    [DataMember]
    public Address Payer { get; set; }

    [DataMember]
    public Package[] Parcels { get; set; }

    [DataMember]
    public DateTime? ShipmentDate { get; set; }

    [DataMember]
    public string Comment { get; set; }

    [DataMember]
    public string Content { get; set; }

    [DataMember]
    public string Reference { get; set; }
}

and

[DataContract]
public class Address : EntityBase
{
    [DataMember]
    public string Company { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Post { get; set; }
    [DataMember]
    public string City { get; set; }
    [DataMember]
    public string Street { get; set; }
    [DataMember]
    public string CountryCode { get; set; }
    [DataMember]
    public string Phone { get; set; }
    [DataMember]
    public string Email { get; set; }        
}

I want to use a method to read the value of specified properties of all classes in one set at a time and fill them to a TreeView. There could be many levels of class. The method (e.g. GetProperty method) should only know about its parameter type, and the string representation of all properties. The method only read property. below is what I've done so far:

public static void GetAllProperties(object entity)
{
    System.Type oType = null;
    try
    {
        oType = entity.GetType();

        PropertyInfo[] cProperties;

        cProperties = oType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (PropertyInfo theProperty in cProperties)
        {
            if (theProperty.PropertyType.IsClass)
            {
                GetAllProperties(theProperty.GetValue(entity, null));
            }
            else
            {
                // use theProperty.GetValue(entity, null).ToString();
            }
        }
    }
    catch (Exception theException)
    {
        
    }
}

This line:

GetAllProperties(theProperty.GetValue(entity, null));

gives me:

Object reference not set to an instance of an object





mercredi 20 juillet 2022

Possible to Divert/Forward Functions in Android?

Assalam wa alaikum! Greetings!

I just wanted to know if there is any way to divert/forward a system class's methods. Means to change it's function while in app.

Example: One of my Jar libraries is using java.io.File 's method length() several times. I want to edit/code the length() (like some kind of inheritance but not really) and make it cache the length so speeds up the process.

Note: It's just an example

Maybe some kind of reflection am expecting. Thanks in advance :-D





Domain based routing by a base controller

I have a multi-domain application.

Currently, I'm using [Host("domain.com")] to distinguish controllers.

At the same time, I have custom base controllers for each application, so I want to simplify this a bit. Ideally, I want to get all controllers inherited from a specified type and require them to be served from a specific domain.

  1. I don't use a custom endpoint configuration, so RequireHost will not work
  2. I'm trying avoiding to create a custom PolicyMatcher. In common, I can copy-paste the existing policy and inject some matching strategy e.g. base class checks, etc. But I'd rather not to do that.
  3. I don't want to use HostAttribute, or at least to subclass it (but it is sealed) to create a pre-defined attribute for the exact domain

Is there another option to implement a domain routing based on a base controller, or to address this requirement?





how to get value of properties with reflection in List?

            List<T> Data = new List<T>();
            var type = typeof(T).GetProperties();

            for (int i = 0; i < Data.Count; i++)
            {
                foreach (var item in type)
                {
                    if (GetTypeOfProp(item) == 1)
                    {
                        worksheet.Range[GetCol(Col) + Row].Text = item.Name;
                        worksheet.Range[GetCol(Col) + (Row + 1)].Text = (item.GetValue(Data[i], null) ?? "").ToString();
                        Col = Col + 1;
                    }
                    else if (GetTypeOfProp(item) == 2)
                    {
                        int OldCol = Col;
                        foreach (var li in item.PropertyType.GetProperties())
                        {
                            worksheet.Range[GetCol(Col) + (Row + 1)].Text = li.Name;

                            var value = li.GetValue(item, null);     // How Can I Get this Value ?

                            Col = Col + 1;
                            MaxRecOfRow = 1;
                        }

                        worksheet.Range[$"{GetCol(OldCol) + Row}:{GetCol(Col - 1) + Row}"].Merge();
                        worksheet.Range[$"{GetCol(OldCol) + Row}:{GetCol(Col - 1) + Row}"].Text = item.Name;

                    }
                    else if (GetTypeOfProp(item) == 3)
                    {
                        worksheet.Range[GetCol(Col) + Row].Text = item.Name;
                        worksheet.Range[GetCol(Col) + (Row + 1)].Text = "";
                        Col = Col + 1;
                        MaxRecOfRow = 1;
                    }
                }
                Row++;
             }

I can get value with reflection in c# with root but this question is get value with (model in model) How Can I Get this Value ? var value = li.GetValue(item, null);





Mongodb C# - Registering class maps with generics works, where using types fails

I have a collection of objects, and each object has a property, EventData, that is many different types. These types all inherit from an IEventData interface.

For example:

{ _id: '...', EventData: { _t: 'TypeA', ... } }
{ _id: '...', EventData: { _t: 'TypeB', ... } }

I'm currently facing an issue with the MongoDB C# driver when trying to register class maps. When using the generic version to register the class map, the EventData object is correctly serialised with all properties and the type discriminator:

BsonClassMap.RegisterClassMap<TypeA>();
// Full event data is written to collection
// { _id: '...', EventData: { _t: 'TypeA', InterfaceProperty: '...', ClassProperty: '...' } }

This works fine, however I have a large amount of different event types, and want to try and use some reflection to help automate this. When trying to use the non-generic version of the RegisterClassMap whilst iterating over all types that implement the IEventData interface, only the interface members are serialised:

var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(i => i.GetTypes())
.Where(t => typeof(IEventData).IsAssignableFrom(t));

foreach (var type in types)
{
    // If it's an interface, skip as we can't register those
    if (type.IsInterface)
        continue;
        
    if (!BsonClassMap.IsClassMapRegistered(type))
       BsonClassMap.RegisterClassMap(new BsonClassMap(type));
        
 }

// Only the interface properties are written to collection
// { _id: '...', EventData: { _t: 'TypeA', InterfaceProperty: '...' } }

Is there some property or something I'm missing to set when using the non-generic type to register the class maps that allow the full type to stored in the collection?

Thanks Justin





mardi 19 juillet 2022

How to call all methods in the current package that have a certain @Annotation?

Lets say i have a method in some class in my application's package:

import org.junit.jupiter.api.Test;

@Test
public void testFizBuzz() {
    if (1 != 0) 
       throw new Exception("Test failed");
}

I want to:

  • enumerate all classes/methods in the "current" package
  • find methods tagged with a specified @Annotation
  • construct the class
  • call the (parameterless) method

How can i do this in Java?

In .NET it's easy

Here's how you do it in .NET (in pseudo-Java):

//Find all methods in all classes tagged with @Test annotation, 
//and add them to a list.
List<MethodInfo> testMethods = new ArrayList<>();

//Enumerate all assemblies in the current application domain
for (Assembly a : AppDomain.currentDomain.getAssemblies()) {
   //Look at each type (i.e. class) in the assembly
   for (Type t : a.getTypes()) {
      //Look at all methods in the class. 
      for (MethodInfo m : t.getMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
         //If the method has our @Test annotation defined: add it
         if (m.IsDefined(typeof(org.junit.jupiter.api.Test), true)) 
            testMethods.add(m);
      }
   }
}

And now that we have a List of all methods with the @Test annotation, it's just a matter of calling them:

//Call every test method found above
for (MethodInfo m : testMethods) {
   Object o = Activator.CreateInstance(m.DeclaringType); //Construct the test object
   m.Invoke(o, null); //call the parameterless @Test method
}

What is the JRE equivalent of the above?

Research Effort





Why a Scala 2.13 app is trying to use `JavaClassValue` on Android if it is not available, then triggering `java.lang.NoClassDefFoundError`?

I'm running a Scala app on Android using https://github.com/dsvdsv/scala-android-plugin and Scala 2.13.8 and I get these weird stack traces on the logs:

07-19 11:46:26.057  3647  3647 I zygote64: Rejecting re-init on previously-failed class java.lang.Class<scala.runtime.ClassValueCompat$JavaClassValue>: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/ClassValue;
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.reflect.ClassTag scala.reflect.ClassTag$.apply(java.lang.Class) (ClassTag.scala:157)
07-19 11:46:26.057  3647  3647 I zygote64:   at void fr.acinq.eclair.wire.CommonCodecs$.<clinit>() (CommonCodecs.scala:153)
07-19 11:46:26.057  3647  3647 I zygote64:   at void immortan.wire.ExtCodecs$.<clinit>() (ExtCodecs.scala:24)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.collection.immutable.List immortan.sqlite.SQLiteData.$anonfun$tryGetMnemonics$1(scodec.bits.ByteVector) (SQLiteData.scala:54)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object immortan.sqlite.-$$Lambda$tPYNHLDkOzKQyc6N9riH1kDlNaQ.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.util.Try scala.util.Success.map(scala.Function1) (Try.scala:262)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.util.Try immortan.sqlite.SQLiteData.tryGetMnemonics() (SQLiteData.scala:52)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:60)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:54)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.$anonfun$onResume$5(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.MainActivity.$anonfun$onResume$5$adapted(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.-$$Lambda$n_HFoagsPQeELoRoOgqfWtzRrXY.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity.$anonfun$runFutureProcessOnUI$2(scala.Function1, java.lang.Object) (BaseActivity.scala:281)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.-$$Lambda$7sLNsOLl1sATbfGX3ztJ04hnydE.apply$mcV$sp() (lambda:-1)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object scala.runtime.java8.JFunction0$mcV$sp.apply() (JFunction0$mcV$sp.scala:18)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity$$anon$6.run() (BaseActivity.scala:295)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.os.Handler.handleCallback(android.os.Message) (Handler.java:789)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:98)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.os.Looper.loop() (Looper.java:169)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6595)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
07-19 11:46:26.057  3647  3647 I zygote64:   at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:240)
07-19 11:46:26.057  3647  3647 I zygote64:   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:767)
07-19 11:46:26.057  3647  3647 I zygote64: Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.ClassValue" on path: DexPathList[[zip file "/data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/base.apk"],nativeLibraryDirectories=[/data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/lib/arm64, /data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:93)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:379)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.reflect.ClassTag scala.reflect.ClassTag$.apply(java.lang.Class) (ClassTag.scala:157)
07-19 11:46:26.057  3647  3647 I zygote64:   at void fr.acinq.eclair.wire.CommonCodecs$.<clinit>() (CommonCodecs.scala:153)
07-19 11:46:26.057  3647  3647 I zygote64:   at void immortan.wire.ExtCodecs$.<clinit>() (ExtCodecs.scala:24)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.collection.immutable.List immortan.sqlite.SQLiteData.$anonfun$tryGetMnemonics$1(scodec.bits.ByteVector) (SQLiteData.scala:54)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object immortan.sqlite.-$$Lambda$tPYNHLDkOzKQyc6N9riH1kDlNaQ.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.util.Try scala.util.Success.map(scala.Function1) (Try.scala:262)
07-19 11:46:26.057  3647  3647 I zygote64:   at scala.util.Try immortan.sqlite.SQLiteData.tryGetMnemonics() (SQLiteData.scala:52)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:60)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:54)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.$anonfun$onResume$5(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.MainActivity.$anonfun$onResume$5$adapted(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.-$$Lambda$n_HFoagsPQeELoRoOgqfWtzRrXY.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity.$anonfun$runFutureProcessOnUI$2(scala.Function1, java.lang.Object) (BaseActivity.scala:281)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.-$$Lambda$7sLNsOLl1sATbfGX3ztJ04hnydE.apply$mcV$sp() (lambda:-1)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object scala.runtime.java8.JFunction0$mcV$sp.apply() (JFunction0$mcV$sp.scala:18)
07-19 11:46:26.057  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity$$anon$6.run() (BaseActivity.scala:295)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.os.Handler.handleCallback(android.os.Message) (Handler.java:789)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:98)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.os.Looper.loop() (Looper.java:169)
07-19 11:46:26.057  3647  3647 I zygote64:   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6595)
07-19 11:46:26.057  3647  3647 I zygote64:   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
07-19 11:46:26.057  3647  3647 I zygote64:   at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:240)
07-19 11:46:26.057  3647  3647 I zygote64:   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:767)
07-19 11:46:26.057  3647  3647 I zygote64:
07-19 11:46:26.058  3647  3647 I zygote64: Rejecting re-init on previously-failed class java.lang.Class<scala.runtime.ClassValueCompat$JavaClassValue>: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/ClassValue;
07-19 11:46:26.058  3647  3647 I zygote64:   at scala.reflect.ClassTag scala.reflect.ClassTag$.apply(java.lang.Class) (ClassTag.scala:157)
07-19 11:46:26.058  3647  3647 I zygote64:   at void fr.acinq.eclair.wire.CommonCodecs$.<clinit>() (CommonCodecs.scala:153)
07-19 11:46:26.058  3647  3647 I zygote64:   at void immortan.wire.ExtCodecs$.<clinit>() (ExtCodecs.scala:24)
07-19 11:46:26.058  3647  3647 I zygote64:   at scala.collection.immutable.List immortan.sqlite.SQLiteData.$anonfun$tryGetMnemonics$1(scodec.bits.ByteVector) (SQLiteData.scala:54)
07-19 11:46:26.058  3647  3647 I zygote64:   at java.lang.Object immortan.sqlite.-$$Lambda$tPYNHLDkOzKQyc6N9riH1kDlNaQ.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.058  3647  3647 I zygote64:   at scala.util.Try scala.util.Success.map(scala.Function1) (Try.scala:262)
07-19 11:46:26.058  3647  3647 I zygote64:   at scala.util.Try immortan.sqlite.SQLiteData.tryGetMnemonics() (SQLiteData.scala:52)
07-19 11:46:26.058  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:60)
07-19 11:46:26.058  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:54)
07-19 11:46:26.058  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.$anonfun$onResume$5(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.058  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.MainActivity.$anonfun$onResume$5$adapted(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.058  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.-$$Lambda$n_HFoagsPQeELoRoOgqfWtzRrXY.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.058  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity.$anonfun$runFutureProcessOnUI$2(scala.Function1, java.lang.Object) (BaseActivity.scala:281)
07-19 11:46:26.058  3647  3647 I zygote64:   at void wtf.nbd.obw.-$$Lambda$7sLNsOLl1sATbfGX3ztJ04hnydE.apply$mcV$sp() (lambda:-1)
07-19 11:46:26.058  3647  3647 I zygote64:   at java.lang.Object scala.runtime.java8.JFunction0$mcV$sp.apply() (JFunction0$mcV$sp.scala:18)
07-19 11:46:26.058  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity$$anon$6.run() (BaseActivity.scala:295)
07-19 11:46:26.058  3647  3647 I zygote64:   at void android.os.Handler.handleCallback(android.os.Message) (Handler.java:789)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:98)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.os.Looper.loop() (Looper.java:169)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6595)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
07-19 11:46:26.059  3647  3647 I zygote64:   at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:240)
07-19 11:46:26.059  3647  3647 I zygote64:   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:767)
07-19 11:46:26.059  3647  3647 I zygote64: Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.ClassValue" on path: DexPathList[[zip file "/data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/base.apk"],nativeLibraryDirectories=[/data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/lib/arm64, /data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:93)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:379)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
07-19 11:46:26.059  3647  3647 I zygote64:   at scala.reflect.ClassTag scala.reflect.ClassTag$.apply(java.lang.Class) (ClassTag.scala:157)
07-19 11:46:26.059  3647  3647 I zygote64:   at void fr.acinq.eclair.wire.CommonCodecs$.<clinit>() (CommonCodecs.scala:153)
07-19 11:46:26.059  3647  3647 I zygote64:   at void immortan.wire.ExtCodecs$.<clinit>() (ExtCodecs.scala:24)
07-19 11:46:26.059  3647  3647 I zygote64:   at scala.collection.immutable.List immortan.sqlite.SQLiteData.$anonfun$tryGetMnemonics$1(scodec.bits.ByteVector) (SQLiteData.scala:54)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Object immortan.sqlite.-$$Lambda$tPYNHLDkOzKQyc6N9riH1kDlNaQ.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.059  3647  3647 I zygote64:   at scala.util.Try scala.util.Success.map(scala.Function1) (Try.scala:262)
07-19 11:46:26.059  3647  3647 I zygote64:   at scala.util.Try immortan.sqlite.SQLiteData.tryGetMnemonics() (SQLiteData.scala:52)
07-19 11:46:26.059  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:60)
07-19 11:46:26.059  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:54)
07-19 11:46:26.059  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.$anonfun$onResume$5(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.MainActivity.$anonfun$onResume$5$adapted(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.-$$Lambda$n_HFoagsPQeELoRoOgqfWtzRrXY.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.059  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity.$anonfun$runFutureProcessOnUI$2(scala.Function1, java.lang.Object) (BaseActivity.scala:281)
07-19 11:46:26.059  3647  3647 I zygote64:   at void wtf.nbd.obw.-$$Lambda$7sLNsOLl1sATbfGX3ztJ04hnydE.apply$mcV$sp() (lambda:-1)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Object scala.runtime.java8.JFunction0$mcV$sp.apply() (JFunction0$mcV$sp.scala:18)
07-19 11:46:26.059  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity$$anon$6.run() (BaseActivity.scala:295)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.os.Handler.handleCallback(android.os.Message) (Handler.java:789)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:98)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.os.Looper.loop() (Looper.java:169)
07-19 11:46:26.059  3647  3647 I zygote64:   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6595)
07-19 11:46:26.059  3647  3647 I zygote64:   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
07-19 11:46:26.059  3647  3647 I zygote64:   at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:240)
07-19 11:46:26.059  3647  3647 I zygote64:   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:767)
07-19 11:46:26.059  3647  3647 I zygote64:
07-19 11:46:26.060  3647  3647 I zygote64: Rejecting re-init on previously-failed class java.lang.Class<scala.runtime.ClassValueCompat$JavaClassValue>: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/ClassValue;
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.reflect.ClassTag scala.reflect.ClassTag$.apply(java.lang.Class) (ClassTag.scala:157)
07-19 11:46:26.060  3647  3647 I zygote64:   at void fr.acinq.eclair.wire.CommonCodecs$.<clinit>() (CommonCodecs.scala:153)
07-19 11:46:26.060  3647  3647 I zygote64:   at void immortan.wire.ExtCodecs$.<clinit>() (ExtCodecs.scala:24)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.collection.immutable.List immortan.sqlite.SQLiteData.$anonfun$tryGetMnemonics$1(scodec.bits.ByteVector) (SQLiteData.scala:54)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object immortan.sqlite.-$$Lambda$tPYNHLDkOzKQyc6N9riH1kDlNaQ.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.util.Try scala.util.Success.map(scala.Function1) (Try.scala:262)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.util.Try immortan.sqlite.SQLiteData.tryGetMnemonics() (SQLiteData.scala:52)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:60)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:54)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.$anonfun$onResume$5(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.MainActivity.$anonfun$onResume$5$adapted(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.-$$Lambda$n_HFoagsPQeELoRoOgqfWtzRrXY.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity.$anonfun$runFutureProcessOnUI$2(scala.Function1, java.lang.Object) (BaseActivity.scala:281)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.-$$Lambda$7sLNsOLl1sATbfGX3ztJ04hnydE.apply$mcV$sp() (lambda:-1)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object scala.runtime.java8.JFunction0$mcV$sp.apply() (JFunction0$mcV$sp.scala:18)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity$$anon$6.run() (BaseActivity.scala:295)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.os.Handler.handleCallback(android.os.Message) (Handler.java:789)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:98)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.os.Looper.loop() (Looper.java:169)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6595)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
07-19 11:46:26.060  3647  3647 I zygote64:   at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:240)
07-19 11:46:26.060  3647  3647 I zygote64:   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:767)
07-19 11:46:26.060  3647  3647 I zygote64: Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.ClassValue" on path: DexPathList[[zip file "/data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/base.apk"],nativeLibraryDirectories=[/data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/lib/arm64, /data/app/wtf.nbd.obw.dev-hM8iLOxXzgsl9ADHLU7hJA==/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:93)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:379)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.reflect.ClassTag scala.reflect.ClassTag$.apply(java.lang.Class) (ClassTag.scala:157)
07-19 11:46:26.060  3647  3647 I zygote64:   at void fr.acinq.eclair.wire.CommonCodecs$.<clinit>() (CommonCodecs.scala:153)
07-19 11:46:26.060  3647  3647 I zygote64:   at void immortan.wire.ExtCodecs$.<clinit>() (ExtCodecs.scala:24)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.collection.immutable.List immortan.sqlite.SQLiteData.$anonfun$tryGetMnemonics$1(scodec.bits.ByteVector) (SQLiteData.scala:54)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object immortan.sqlite.-$$Lambda$tPYNHLDkOzKQyc6N9riH1kDlNaQ.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.util.Try scala.util.Success.map(scala.Function1) (Try.scala:262)
07-19 11:46:26.060  3647  3647 I zygote64:   at scala.util.Try immortan.sqlite.SQLiteData.tryGetMnemonics() (SQLiteData.scala:52)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:60)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.proceed(java.lang.Object) (MainActivity.scala:54)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.MainActivity.$anonfun$onResume$5(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.MainActivity.$anonfun$onResume$5$adapted(wtf.nbd.obw.MainActivity, java.lang.Object) (MainActivity.scala:43)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object wtf.nbd.obw.-$$Lambda$n_HFoagsPQeELoRoOgqfWtzRrXY.apply(java.lang.Object) (lambda:-1)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity.$anonfun$runFutureProcessOnUI$2(scala.Function1, java.lang.Object) (BaseActivity.scala:281)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.-$$Lambda$7sLNsOLl1sATbfGX3ztJ04hnydE.apply$mcV$sp() (lambda:-1)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object scala.runtime.java8.JFunction0$mcV$sp.apply() (JFunction0$mcV$sp.scala:18)
07-19 11:46:26.060  3647  3647 I zygote64:   at void wtf.nbd.obw.BaseActivity$$anon$6.run() (BaseActivity.scala:295)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.os.Handler.handleCallback(android.os.Message) (Handler.java:789)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:98)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.os.Looper.loop() (Looper.java:169)
07-19 11:46:26.060  3647  3647 I zygote64:   at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6595)
07-19 11:46:26.060  3647  3647 I zygote64:   at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
07-19 11:46:26.060  3647  3647 I zygote64:   at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:240)
07-19 11:46:26.060  3647  3647 I zygote64:   at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:767)
07-19 11:46:26.060  3647  3647 I zygote64:
07-19 11:46:26.543  3647  3653 I zygote64: Do partial code cache collection, code=61KB, data=43KB
07-19 11:46:26.544  3647  3653 I zygote64: After code cache collection, code=61KB, data=43KB
07-19 11:46:26.544  3647  3653 I zygote64: Increasing code cache capacity to 256KB

They happen whenever some code path for some reason touches ClassValue or ClassTag -- which unfortunately happens more often than not inside my dependencies (I've removed everything from my own code and from the dependency usage I could, but that wasn't enough); but weirdly the app doesn't crash, it just runs fine (except it gets a little slow apparently when these errors happen).

Another weird thing is that it seems that it only triggers the error the first time it runs through these code paths (that touch ClassValue), then later the app goes through them many times and the error doesn't happen ever again.

If you look closely it will say it is using ClassValueCompat, which was introduced to fix the lack of java.ClassValue on Android among other things, but then it is not using the FallbackClassValue as it should, it is using JavaClassValue, which was supposed to not exist on Android and is in fact what is causing the error -- so it shouldn't be in use at all.


Notice that ClassValueCompat does this check to determine if it should use JavaClassValue or FallbackClassValue:

private val classValueAvailable: Boolean = try {
  Class.forName("java.lang.ClassValue", false, classOf[Object].getClassLoader)
  true
} catch {
  case _: ClassNotFoundException => false
}

I did this same check on my app initialization code and I got the ClassNotFoundException as expected.





samedi 16 juillet 2022

Javascript, log what causes a boolean expression to fail

I have a complex predicate in JavaScript that chains various tests against a value.

I'd love to log where in the expression it fails, if it fails. Sort of like testing libraries that log out where an exception fails.

Is there some sort of reflection I can do to extract some pretty description of what caused an expression to fail?

e.g.,

const predicate = a.foo == 1 && a.bar < 3 && someOtherPredicate(a.bar)

// if predicate == false, console.log ->
// "error: b.bar < 3 evaluated to false"

(I'm actually interested in doing this in Typescript, but want to see what features JavaScript has that could enable this)




vendredi 15 juillet 2022

How to output a formatted string from a json model class in C#

I want something like the following

using System;
using System.Text;
using System.Text.Json;
                    
public class Program
{
   public static void Main()
   {
      var myArgs = new ArgClass();
        
      // myArgs is populated via System.Text.Json deserialization
        
      Console.WriteLine(myArgs.ToArguments());
   }
}

public interface IArguments{}

public class ArgClass : IArguments
{
   [JsonPropertyName("propertyA")]
   public string PropA {get; set;}
    
   [JsonPropertyName("propertyA")]
   public int PropB {get; set;}
}

public static class IArgumentsExt
{
   public static string ToArguments(this IArguments ArgObj)
   {
      var argString = new StringBuilder();

      //Code to build argument string

      return argString.ToString();
    } 
}

So that the Console.Writeline() would output the following string

-argument propertyA="some text" -argument propertyB=123

I feel like this is something that has to be done with reflection, but I know nothing about reflection. I have tried really hard to avoid situations that require it because everything I read (or watch) says its slow.

The reason I want to do it like this is because the json string that I am deserializing has more properties that I am interested in at to moment, but I might want to use more of them in the future; like if I add more features to my app later. As it stands I can add PropC to ArgClass to pick up another json property. In which case I would want the new output of ToArguments() to be

-argument propertyA="text a" -argument propertyB=123 -argument propertyC="text c"

without having to modify ToArguments().

Or maybe make another class

public class OtherArgClass : IArguments
{
   [JsonPropertyName("propertyD")]
   public string PropD {get; set;}
    
   [JsonPropertyName("propertyE")]
   public int PropE {get; set;}
}

and have an output of myOtherArgs.ToArguments()

-argument propertyD="some other text" -argument propertyE=45.678

again, without modifying ToArguments()

I am using .Net 7 Preview and System.Text.Json (not Newtonsoft/Json.net)





myUrl field is null even though I set it in test setup

I have this test:

@RunWith(MockitoJUnitRunner.class)
public class CollectionManagerTest {

    @InjectMocks
    private CollectionManager collectionManager;

    @Mock
    RestTemplate restTemplate;

    @Captor
    private ResponseEntity<String> responseEntity;

    /**
     *
     */
    @Before
    public void setup() {
        org.springframework.test.util.ReflectionTestUtils.setField(collectionManager, "myUrl", "http://test");
        responseEntity = new ResponseEntity<>("SUCCESS", HttpStatus.OK);
    }

    @Test
    public void createMyStringTest() throws Exception {
        String myString = collectionManager.createMyString("TestDocIsns");
        assertTrue(myString.contains("DOC_ISN=TestDocIsns"));
    }
}

It fails with this error:

ReflectionTestUtils - Setting field 'myUrl' of type [null] on target object [org.me.services.docs.CollectionManager@2dc9b0f5] or target class [class org.me.docs.CollectionManager] to value [http://test]

I thought this would have been set with org.springframework.test.util.ReflectionTestUtils.setField(collectionManager, "myUrl", "http://test");

This is the variable in the actual class:

@Value("${my.url}")
private String myUrl;

What am I doing wrong?





Better way to trim strength lengths in object than reflection

I have a custom annotation defined for trimming strings based on the size specified.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Trim {
    public int size();
}

and an entity where I am using it

@Entity
@Table
@Data
public class Users {

    @Id
    private Long id;

    @Trim(size = 10)
    private String firstName;

    @Trim(size = 10)
    private String middleName;

    @Trim(size = 10)
    private String lastName;

    @Trim(size = 25)
    private String address;

}

The goal is to trim size based on what's specified in the annotation. For ex: the address column has a size constraint of 25 characters on the database table and if the address field contains more than 25 characters we need to trim the string to only consider the first 25 characters prior to calling save() on the entity. This can't be done in code because there are many fields with size constraints in many tables.

This is currently done through reflections and the function below works but I am wondering if there is a better way than this.

    public User trimStrings(User u) throws IllegalAccessException {
        for (Field f : u.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            if (f.get(u) != null && f.isAnnotationPresent(Trim.class)) {
                Trim t = f.getDeclaredAnnotation(Trim.class);
                String str = (String) f.get(u);
                int siz = Math.min(t.size(), str.length());
                f.set(u, str.substring(0, siz));
            }
            f.setAccessible(false);
        }
        return u;
    }




jeudi 14 juillet 2022

Get pointer type of a reflect.Type

Assume I only have a reflect.Type t:

fmt.Println(t) //prints lib.Counter

I would like to get pointer type to this type, such that:

fmt.Println(ptrT) //prints *lib.Counter

How can I do this? t can be of any type, not only lib.Counter.

Also, what if I want to do vice versa? Like getting lib.Counter from *lib.Counter?





How to resolve InaccessibleObjectException for Field.setAccessible in JDK 17?

With JDK 17, it's not possible anymore to make a field accessible using reflection, at least not for java.lang-classes. Following snippet:

final Process process = new ProcessBuilder().directory(new File("d:/temp")).command("cmd.exe").start();
final Field handleField = process.getClass().getDeclaredField("handle");
handleField.setAccessible(true);

fails with:

Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final long java.lang.ProcessImpl.handle accessible: module java.base does not "opens java.lang" to unnamed module @254989ff
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)

Is there a way to work around this problem?





mercredi 13 juillet 2022

Using Scala ClassTags in Collections

I'm trying to create an enum-like type in Scala with a generic type, later doing operations on the instances of the type that depend on what the generic is using Scala's reflect.ClassTag to get information on the generic type. Something like this:

import scala.reflect.ClassTag

sealed trait X[T : ClassTag] {
  def value: T
}

case object I1 extends X[Int] { override def value = 1 }
case object I2 extends X[Int] { override def value = 2 }
case object Sa extends X[String] { override def value = "a" }
case object Sb extends X[String] { override def value = "b" }

val values = IndexedSeq(I1, I2, Sa, Sb)

values.foreach{
  case i: X[Int] => println(s"${i.value} => ${i.value + 1}")
  case s: X[String] => println(s"${s.value} => ${s.value.toUpperCase}")
}

This produces the following warnings:

the type test for Playground.X[Int] cannot be checked at runtime
the type test for Playground.X[String] cannot be checked at runtime

For completeness, when run, it produces the following output (which is reasonable given the warnings):

1 => 2
2 => 3
java.lang.ExceptionInInitializerError
    at Main$.<clinit>(main.scala:24)
    at Main.main(main.scala)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at sbt.Run.invokeMain(Run.scala:143)
    at sbt.Run.execute$1(Run.scala:93)
    at sbt.Run.$anonfun$runWithLoader$5(Run.scala:120)
    at sbt.Run$.executeSuccess(Run.scala:186)
    at sbt.Run.runWithLoader(Run.scala:120)
    at sbt.Run.run(Run.scala:127)
    at com.olegych.scastie.sbtscastie.SbtScastiePlugin$$anon$1.$anonfun$run$1(SbtScastiePlugin.scala:38)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at sbt.util.InterfaceUtil$$anon$1.get(InterfaceUtil.scala:17)
    at sbt.ScastieTrapExit$App.run(ScastieTrapExit.scala:259)
    at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
    at scala.runtime.BoxesRunTime.unboxToInt(BoxesRunTime.java:99)
    at Playground$.$anonfun$1(main.scala:17)
    at scala.runtime.function.JProcedure1.apply(JProcedure1.java:15)
    at scala.runtime.function.JProcedure1.apply(JProcedure1.java:10)
    at scala.collection.immutable.Vector.foreach(Vector.scala:1856)
    at Playground$.<clinit>(main.scala:20)
    ... 17 more

I also tried doing it like this, with the singleton objects implemented as instances of case classes instead:

import scala.reflect.ClassTag

sealed trait X[T : ClassTag] {
  def value: T
}

case class I(value: Int) extends X[Int]
case class S(value: String) extends X[String]

val values = IndexedSeq(I(1), I(2), S("a"), S("b"))

values.foreach{
  case i: X[Int] => println(s"${i.value} => ${i.value + 1}")
  case s: X[String] => println(s"${s.value} => ${s.value.toUpperCase}")
}

But I get pretty much the exact same result.

When I do something that appears to me to be similar using a Scala Array, it works:

val values = IndexedSeq(
  Array(1, 2),
  Array(3, 4),
  Array("a", "b"),
  Array("c", "d")
)
values.foreach{
  case i: Array[Int] => println(s"""${i.mkString(",")} => ${i.map(_ * 2).mkString(",")}""")
  case s: Array[String] => println(s"""${s.mkString(",")} => ${s.map(_.toUpperCase).mkString(",")}""")
}

This produces no warnings and the correct output:

1,2 => 2,4
3,4 => 6,8
a,b => A,B
c,d => C,D

What am I doing wrong here? I thought ClassTag was supposed to preserve information about a generic type during runtime? I've seen that reflect.runtime.universe.TypeTag might be better, but the package containing that doesn't seem to be available in Scala 3, and somehow Array is able to do what I want anyway.





Generic builder for populating properties pattern

I created a builder class to populate properties in my models for testing scenarios

    public partial class ModelBuilder
    {
        private Model myModel;
        public ModelBuilder CreateNew(int id)
        {
            myModel = new Model(id);
            return this;
        }

        public ModelBuilder WithName(string name)
        {
            myModel.Name = name;
            return this;
        }

        public ModelBuilder WithAge(int age)
        {
            myModel.Age = age;
            return this;
        }

        public ModelBuilder WithComplexLogic(int data)
        {
            myModel.ProcesData(data)
            return this;
        }

        public Model Build()
        {
            return myModel;
        }
    }

I can use it like this

var modelBuilder = new ModelBuilder<Model>();
modelBuilder.WithName("Name");
modelBuilder.WithAge(30);
modelBuilder.WithComplexLogic(42);
var model = modelBuilder.Build();

Is it possible to create a more generic version for this so I can use it for other classes without creating new methods for setting simple properties values? I was thinking something with lambda syntax for Name and Age, but ComplexLogic() stays the same.

var modelBuilder = new ModelBuilder<Model>();
modelBuilder.WithProperty(x => x.Name = "Name");
modelBuilder.WithProperty(x => x.Age = 30);
modelBuilder.WithComplexLogic(42);
var model= modelBuilder.Build();





Get navigation property with Reflection in c#

Product Class

public class Product {
   public int Id { get; set; }
   //some properties

   //Navigation Property
   Category Category { get; set; }
}

Category Class

public class Category{
   public int Id { get; set; }
   //some properties

   //Navigation Property
   ICollection<Product> Products { get; set; }
}

i need to get navigation properties in product and category classes. It is enough to get ICollection and Category property name. So, i can exclude while i get columns in entities.

How can i get this properties with reflection?





Use reflection to get entries from a list

I have a LinkedList of Strings

List<String> list = new LinkedList();
list.add("");

Using Reflection, how would I be able to get the Field object of list.get(0) and then set the field object with a value such as "Hello"?

Something like this:

Field field = //the field entry of list.get(0)
field.set() // set field with a string "Hello"




Reflection Methodinfo - how to use remove for a reflected property (List)

My goal is to remove entries from unknown list / collection at compile time.

I'm passing an interface as parameter. With reflection I receive the associated collection and method "Remove".

private void DeleteRowOfUnknownCollection(IMakeClassUsableForStandardGridButton uiModel) {
        Type typView = this.GetType();
        PropertyInfo propInfoCollection = typView.GetProperty(GetCollectionPropertyNameByModel(uiModel));
        object instanceOfCollection = propInfoCollection.GetValue(this);
        Type propTyp = instanceOfCollection.GetType();
        MethodInfo methodRemoveOfCollection = propTyp.GetMethod("Remove");

        object ToBeRemovedUiModel = Activator.CreateInstance(uiModel.GetType());

        methodRemoveOfCollection.Invoke(instanceOfCollection, new [] { ToBeRemovedUiModel } );
    }

Plain and simple - I don't know how to use the Remove method when its reflected and expecting an object intantiated with new.

Any ideas how to remove the passed uiModel?

Thanks in advance!





mardi 12 juillet 2022

How to get a field reference in java?

i am trying to get a compile time safe field reference in java, done not with reflection and Strings, but directly referencing the field. Something like

MyClass::myField

I have tried the usual reflection way, but you need to reference the fields as strings, and this is error prone in case of a rename, and will not throw a compile time error





How to convert string to func using reflect.MakeFunc?

I'm trying to create a function from a string value, this code returns a function however when calling StringToFunc("funcB") a memory address is returned. Ex: 0x1092880

func StringToFunc(inputString string) interface{} {
    funcType, funcValue := reflect.TypeOf(func() {}), reflect.ValueOf(inputString)

    return reflect.MakeFunc(funcType, func(input []reflect.Value) []reflect.Value {
        newFunc := funcValue.Call(input)
        return newFunc
    }).Interface()
}

Ultimately I'm trying to create a function for every element in a Map, constructing the function using the string value assigned to the key.

Example map is "funcB":"funcB" to type map[string]interface{} using StringToFunc() which returns map[funcB:0x1092880].





How to set or get Button1.FlatAppearance.BorderColor with reflection

How can I use Reflection to set or retrieve the FlatAppearance.BorderColor property of a Button object? Experiments with VB code ...

'MyObject refers to an existing Button object

Dim MyType As Type = MyObject.GetType

Dim MyPropertyInfo As PropertyInfo

PropertyInfo = MyType.GetProperty("FlatAppearance.BorderColor")

But above VB code fails and gives nothing back





How to set annotations on a method using reflection?

I'm trying to unit test an aspect.

    val joinPoint = mock<ProceedingJoinPoint>()
    val methodSignature = mock<MethodSignature>()

    val roleArray = arrayOf("someTestRole")
    val annotation = AccessCheck::class.constructors.first().call(roleArray)
    val method = this.javaClass.getMethod("myMethod")
    method.setAccessible(true)
a)  method.annotations = roleArray
b)  method.annotations[0] = annotation

Cannot invoke b) because method.annotations returns null.
Cannot invoke a) because method.annotations is val.
Cannot make Method a mock, since it's a final class.

Is there any way to surpass that?

This is what annotation class looks like:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class AccessCheck(val userRoles: Array<String>)




lundi 11 juillet 2022

Determine whether a C# Record implements custom Equality comparison by reflection

Is it possible to know whether a Record type has a custom implementation of the Equals method using reflection?

For example, with the following code:

public sealed record A
{
    public long Id { get; init; }
}

public sealed record B
{
    public string Name { get; init; }

    public bool Equals(B other) => StringComparer.InvariantCultureIgnoreCase.Equals(this.Name, other.Name); 
    public override int GetHashCode() => StringComparer.InvariantCultureIgnoreCase.GetHashCode(this.Name);
}

I would like a method which could return:

HasCustomEqualityImplementation(typeof(A)); // false
HasCustomEqualityImplementation(typeof(B)); // true

It does not seem obvious, as the compiler automatically generates an Equals method for record A, and I didn't find a way to differentiate it from the explicit implementation from record B, but I may have missed something.





dimanche 10 juillet 2022

How do you get Java reflections to look for multiple levels of annotation

I'm trying to get multiple levels of annotation in one go. I find it kind of hard to explain in words, so let's consider the following example.

@Controller
public @interface HttpController {
}

@Controller
public @interface ConsoleController {
}

public @interface Controller{
}

If I have the above annotations, I would like to get every class annotated with any of these with only needing to do reflections.getTypesAnnotatedWith(Controller.class);

I've tried reflections.getTypesAnnotatedWith(Controller.class, true); and I know that I could just search for each of them separately, but I'd love to just be able to add a new Controller annotation with only needing to annotate that annotation with @Controller.

I have currently built my Reflection like this:

new Reflections(
        new ConfigurationBuilder()
              .setUrls(
                      ClasspathHelper.forPackage(
                      rootClass.getPackageName()))
              .setScanners(new SubTypesScanner(false),
                      new TypeAnnotationsScanner())
              .filterInputsBy(it ->
                      it.startsWith(rootClass.getPackageName())));




How I can call a method by one string in Swift ? (On IOS)

Hi everyone I want to call one method inside my class using only one string. I know this type of manipulation it's called Reflection but i don't have find anything on web. And if this is possible how I can call a method with parameters ? Thank you.





samedi 9 juillet 2022

Can JavaScript override variable values using another closure at runtime?

Say I want to use one function to 'decorate' another with input/output. But I want this wrapping to be optional, and if used, the function wrap 'shadows' the variable within the closure.

I have an object called customSettings that contains lambda functions that can be called, and also uses the variable 'green' within.

In 'wrap' I try to override the green variable value. Can I avoid hardcoding the variable name 'green' in 'wrap'?

Eventually I'm thinking 'wrap' will be the generalized function, and the user uses it to define wrappingFunc, where for example the anonymous function '(g)=>' returns an object. Then for each value that exists inside the object structure (eg. obj['greens']), it overrides variable's value within the context of the closure of the function specified.

Running the code with 'green' hardcoded also doesn't work -- the original closure's variable value is still being used.

Is this sort of variable name overriding possible in JavaScript? If not any pointers to this scenario?

    let greens = 100;
    // Defined object structure with specified keyword 'color' to be called by another function
    let customSettings: DrawSettingLambdas = new DrawSettingLambdas(GlobalDrawSetting, {
      color: () => {
        // Issue is here: I want to wrap this lambda object eventually with 'wrap', but I don't want to let the variable name 'greens' be hardcoded. Now I can hardcode a 'common' variable contextObj but then I can't use it for normal use cases now.
        // If i use 'greens', I'll have to write greens in the function below.
        //greens
        return ColorConversions.rgbToHex(0, contextObj['green'], 0);
      }
    });


    // Quick wrap
    function wrap(obj, contextLambda) {
      return (inputLambda) => {
        // Variable name contextObj is hardcoded.
        let contextObj = {"green": contextLambda(inputLambda)};
        return obj;
      }
    }
    
    // eg. greens 1, 2, 3 returns the correct context numbers....
    let wrappingFunc = wrap(customSettings, (g)=>{return g * 100;});
    
    // Use wrap
    draw.AddGraph(subtractResults3, canvasRectangle3, [], wrappingFunc(1));
    draw.AddGraph(subtractResults2, canvasRectangle3, [], wrappingFunc(2));
    draw.AddGraph(subtractResults1, canvasRectangle3, [], wrappingFunc(3));




vendredi 8 juillet 2022

Concatenating Lists at runtime

I am handling classes that wrap collections. For example:

public class CollA 
{
  public List<SomeType> Items {get;set;}

  // other properties I'm not interested in
}

I am guaranteed that the collection classes will have exactly ONE property that is of List<T>

Now, I find myself with a requirement such that I may have many instances of CollA and I am asked to return a new instance of CollA where the property Items contains a union of the Items properties of the individual CollA instances. So, for example:

var A = new CollA(Items = new List<SomeType> 
{
  new SomeType("A"), new SomeType("B")
};
var B = new CollA(Items = new List<SomeType> 
{
  new SomeType("C"), new SomeType("D")
};

var result = SomeMythicalCombine(A, B);

// result.Items == { new SomeType("A"), new SomeType("B"), new SomeType("C"), new SomeType("D") }

This, if the types are all known at compile time is easy, but I need to do it with the types not being known until runtime.

I've got part of the way, I think, using reflection....

public T SomeMythicalCombine (params object[] collections)
{
    var collectionType = typeof(T);
    
    var listProperty = collectionType.GetProperties()
        .Single(p=> typeof(IList).IsAssignableFrom(p.PropertyType));

    var listPropertyName = listProperty.Name;

    var result = Activator.CreateInstance(collectionType);

    var innerType = listProperty.PropertyType.GenericTypeArguments[0];
    var listType = typeof(List<>).MakeGenericType(innerType);
    var list = Activator.CreateInstance(listType);
    
    foreach(var collection in collections)
    {
        var listValues = collection.GetType().GetProperty(listPropertyName).GetValue(collection);
        
        // listItems is an object here and I need to find a way of casting it
        // to something I can iterate over so I can call (list as IList).Add(something)
    }   
    
    // Then, I think, all I need to do is set the appropriate property on the 
    // the result item
    result.GetType().GetProperty(listPropertyName).SetValue(result, list);
    
    return result as T;
}

Can anyone fill in the gap in my thinking, please?





Unexpected behaviour with generics

I'm facing this error while work with Java generics, and I don't understand which is the problem;
I have two classes like these:

public abstract class BaseClass{
   ....
}

public class OneClass extends BaseClass{
   ....
}

I have a generic repo for OneClass:

public class MyRepo<T extends BaseClass>{
   List<T> getElements();
}

Then I have a method that should works whit generics:

private MyRepo<OneClass> myRepo;   

public <T extends BaseClass> List<T> myMethod(){
     return myRepo.getElements();
}

The method doesn't work unless I force a cast to List ( as shown below ):

public <T extends BaseClass> List<T> myMethod(){
   return  (List<T>)  myRepo.getElements();
}

I don't understand which is the problem given that OneClass extends BaseClass.
Thanks for any suggestion.





jeudi 7 juillet 2022

Make modification to method argument before the method gets called

What would be the best way to perform some modification on a method argument before the method is actually executed?

I have tried achieving this with a combination of attributes and use of the decorator/proxy pattern:

#[\Attribute]
class Query
{
}

class Foo
{
   #[Query]
   public function request(array $query = [])
   {
   }

   public function foo(array $query = [])
   {
   }

   #[Query]
   public function bar(string $name, int $age, array $query = [])
   {
   }
}

class FooDecorator
{
   private Foo $target;

   public function __construct(Foo $target)
   {
      $this->target = $target;
   }

   public function __call(string $methodName, array $args)
   {
      $class = get_class($this->target);
      try {
        $reflection = new \ReflectionClass($class);
        $methods = $reflection->getMethods();
        $attributeName = __NAMESPACE__ . '\Query';
        foreach ($methods as $method) {
            if ($method->getName() !== $methodName) {
                continue;
            }
            $attributes = $method->getAttributes();
            foreach ($attributes as $attribute) {
                if ($attribute->getName() === $attributeName) {
                    $parameters = $method->getParameters();
                    foreach ($parameters as $key => $param) {
                        if ($param->getName() === 'query') {
                            // Here we filter the parameter named 'query'
                            $args[$key] = $this->validateQueryParameter($args[$key]);
                            break;
                        }
                    }
                }
            }
        }
      } catch (\Exception $e) {
      }
      if (method_exists($this->target, $methodName)) {
          return call_user_func_array([$this->target, $methodName], $args);
      }
   }

   private function validateQueryParameter(array $query): array
   {
      $allowed = [
        'foo',
        'bar',
      ];
      $query = array_filter($query = array_change_key_case($query), function ($key) use ($allowed) {
        // Filter out any non-allowed keys
        return in_array($key, $allowed);
      }, ARRAY_FILTER_USE_KEY);
      return $query;
   }
}

$foo = new FooDecorator(new Foo());
// Should remove faz & baz, but keep foo in the query
$foo->query(['faz' => 1, 'baz' => 2, 'foo' => 3]);
// Should not perform anything on the query parameter
$foo->foo(['baz' => 1]);
// Should remove faz & baz, but keep foo in the query
$foo->bar('foo', 100, ['faz' => 1, 'baz' => 2, 'foo' => 3]);

This works as expected, but since I am using a decorator here I am now missing the hints for each method included in the Foo class.

I know that I could use an interface and declare all methods included in `Foo´, but then I would need to implement every method (the real class contains many many methods) in the decorator, which seems like overkill.





Reflection with Delegates

I'm using reflection to compare two list of objects(of same type) and collecting the list of properties which have different values. I may iterate through lakhs of object list to compare which ended in performance lag. I came to know about using delegates in the reflection so we can bypass the .GetValue(obj, null) which is taking time. The types of my class properties is wide. It can be string, int and enum. The available solutions are not working out for me. Thanks for your help.

The code I'm using to compare the 2 objects of same type

public List<string> Compare<T>(object A, object B)
{
                var type = typeof(T);
                var allProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                List<string> unequalProperties =
                    (
                        from pi in allProperties 
                        let AValue = type.GetProperty(pi.Name).GetValue(A, null)
                        let BValue = type.GetProperty(pi.Name).GetValue(B, null)
                        where AValue != BValue && (AValue == null || !AValue.Equals(BValue))
                        select pi.Name
                    ).ToList();
                return unequalProperties;
}

The two .GetValue(A/B, null) is producing the lag which i want to skip using delegates.





Find out all the function properties in JavaScript [duplicate]

How could I find out all the function properties in JavaScript?

Here is what I tried:

var a = function(a, b, c) {};
a.length;
Object.keys(a);

enter image description here

So, the a definitely has the length property (with the value of 3), but for some reasons there is no "length" in the array produced by the Object.keys(a);. Why? How could I see all the function properties? I am interested to know both personal and inherited (using the proto) properties.

I am interested in this purely due to desire to learn and explore the intricacies of JavaScript. I do not have any real world application for this knowledge right now.





mercredi 6 juillet 2022

Golang: Validate tags at compile time

I have written a custom tag reader using reflect package. Example:

type SomeStruct struct {
    Var1 customType `customTag:"prop1:hello;prop2:0.15,0.1;prop3:0.15=2,3=4.1"`
}

The tags are written in a specific format for my custom tag reader. I would like to catch problems (if any) in the tags at the compile itself. How can I achieve that?





How to serialize and deserialize user-defined types? [duplicate]

I'm trying to write my own game engine and I want the user to be able to use custom POD components. In order to save them in a scene file I need to find a way to (de)serialize them. Unity and Godot probably handle this with reflection, while I believe Unreal "simulates reflection" through code generation, which is probably too much for my project. Should I just stick to (de)serialize only map data (like static meshes and light sources), "hardcoding" every scene in a different way?

Edit: I need to be able to deserialize user-defined types; this means that my engine might be unaware of a Transform component. However, if it's serialized in a YAML or JSON format, I need a function that handles that string and populates the scene accordingly. I've thought about a map whose keys are component names (as strings) and values are pointers to deserialize functions, but how would the user intuitively register those functions?





dart language: How to get all the classes available to import?

Programmatically I want to get all dart files available to import. How can I achievement this? (programmatically)





Dynamically checking subclass relationship in Scala 3

I am trying to port a solution for DomainEventHandlers and -Dispatcher from PHP8 to Scala 3. Handlers should specify a list of events they can handle (in a type-safe way, preferably, by their classes). Handlers are dynamically registered with the Dispatcher, which should aggregate a map from the elements of the lists from each Handler to a List of Handlers for those events.

When an event is raised with the Dispatcher, it should check the class of the current event against the keys from the map, and pass the event to each Handler in each list of Handlers for a key if and only if the event's class is identical to or a subclass of the class specified by the key.

In dynamically typed OOP languages like PHP8, this is easy - a Handler stores a list of class-names, which can be reified simply by [ClassName]::class, then the Dispatcher gets the event's class via $event::class and performs an is_a-check for each HashMap-key, which checks both exact match and subclass-relationship.

In Scala 3, I can't seem to find a good way to do this. Working with underlying Java-reflections via getClass or Class[?] produces problems due to the mismatch between the Scala and Java type-systems (specifically, trailing $ being either present or not). In Scala 2, Tags would probably have been the way to go - but Scala 3 reflection is a different beast, and I have not found a way to utilize it to implement the above, and would appreciate advice.

Concretely, let's say we have

trait DomainEvent[D1 <: Serializable, D2 <: Serializable, A <: Aggregate]
extends Event[D1, D2]:
  type AggregateType = A
  val aggregateIdentifier: (String, UUID)
  def applyAsPatch(aggregate: AggregateType): AggregateType

trait DomainEventHandler:
  val handles: List[???]
  def handle(event: DomainEvent[?, ?, ?]): ZIO[Any, Throwable, Unit]

object DomainEventDispatcher:
  val registeredHandlers: scala.collection.mutable.Map[???, List[DomainEventHandler]] = 
      scala.collection.mutable.Map()
  def registerHandler(handler: DomainEventHandler): Unit = ???
  def raiseEvent(event: DomainEvent[?, ?, ?]): ZIO[Any, Throwable, Unit] = ???

I am unsure what to use in place of ??? in the DomainEventHandler's List and the Dispatcher's Map - the registerHandler and raiseEvent-implementations will follow from that.





Dynamically generate and return a class object

In my database I have a product_type ('prod1' | 'prod2' | 'prod3').

I would like to generate a class object based on its type.

Here's my TypeScript code:

interface Product {
  readonly type: string;
  name(): string;
}

class Product1 implements Product {
  readonly type: string = 'prod1';
  name: () => 'Product 1';
}
class Product2 implements Product {
  readonly type: string = 'prod2';
  name: () => 'Product 2';
}
class Product3 implements Product {
  readonly type: string = 'prod3';
  name: () => 'Product 3';
}

function getProductByType(type: string) {
  // TODO: return Product1, Product2 or Product3
  if (type == 'prod1') return new Product1();
  else if (type == 'prod2') return new Product2();
  else return new Product3();
}

The problem is in the getProductByType function. Is there an approach to return a concrete Product class based on the passed type without having multiple if-else statements?

This sounds like a good case for a factory strategy pattern but I can't figure out how to correctly implement it here...





mardi 5 juillet 2022

How could I check in JavaScript if the function I am calling is expecting an argument?

There is the documentation for Mocha. There is the following code sample:

it('should take less than 500ms', function (done) {
  this.timeout(500);
  setTimeout(done, 300);
});

Also, the following test is valid:

it('should take less than 500ms', function () {
});

What JavaScript tools does Mocha use to determine if someone will use the done or not?

E.g. if I have a method:

function incrementIfExpectsSomething(callback) {
    if(/*callback has a parameter in its definition*/) {
        //increment
    }
}

How could I implement the /*callback has a parameter in its definition*/ part?

I do not have any applications straight away. I am asking this question just to have a better knowledge of the JavaScript.





cast object Task

I'm making a unit test class with a config file. I have similar object (same interfaces) to check.

At a point of my code I get Task<ActionResult<OneOfMyObjectType>> object by using reflection. my issue is to read the Result I have to cast this Object First but I can't use Task<IActionResult> or Task<ActionResult<InferfaceOfTheObject>>. the compiler only allow me to cast to the Specific class that is used. (if I don't I have an InvalidCastException).

How Can I do this?

extract of code of my tests :

dynamic objectType = Type.GetType($"{ClassName},{Assembly}")!;
Type ControllerActionType = Type.GetType($"{ControllerActionsClasseName}, {Assembly}")!;
MethodInfo info = ControllerActionType.GetMethod(methodName!)!;
var myInstance = Activator.CreateInstance(ControllerActionType, new object[] { context });
var testObject = JsonConvert.DeserializeObject(operation!.Data, objectType);
var actionResult = info!.Invoke(myInstance, new object[] { testObject })!;
var castedActionResult = "** I'm blocked here**";




how can i load a dll and assign routing url to methods to use them as webAPI calls?

i'm writing an application in asp.net core with a set of webAPI defined usig MVC and routing attributes. Now i'd like to manage additionals functions but, as a plugin, i'm going to define them in a external DLL and then load it with

Assembly assemblyPlugin = Assembly.LoadFrom(DLL2load);

This is ok but how can i be able to call its methods as webAPI from anotther application ? May i have to define their routing attributes inside the loaded DLL or to assign them after loading it in the main application? How can i do it ?