vendredi 29 septembre 2023

Propertyinfo not returning properties of a nested type

I am trying to retrieve the properties of a nested type. Here is the code to retrieve properties, including nested properties using recursion. All of the properties are returned but the properties of the nested property are not returning after it hits the getproperties() method.


 public class Employee
    {
    
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
        public DateTime BirthDate { get; set; }
        public IEnumerable<Paycheck> Paychecks { get; set; }
        public string SocialSecurityNumber { get; set; }

    }

public class Address
    {

        public string AddressOne { get; set; }
        public string AddressTwo {get;set;}
        public string City { get; set; }
        public string State { get; set; }
        public Zip Zip { get; set; }

    }

public List<LoggedObjectProperty> GetItems<T>(T obj)
        {
          
            var ret = new List<LoggedObjectProperty>();

            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
            foreach (PropertyInfo property in properties)
            {
                
              
                    if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
                    {
                       
                        if (obj == null) { return null; }

                        Type type = obj.GetType();

                        PropertyInfo info = type.GetProperty(property.Name);

                        if (info == null) { return null; }
                        var v = info.GetValue(obj, null);

                        if (v != null)
                            GetItems(v);

                    }

                }

            }

            return ret;

        }



I expected to see the properties of the nested type but no properties were returned.




mercredi 27 septembre 2023

Create pointer with inited object from pointer type in generic struct

type TypedConnection[Receive, Send proto.Message] struct {
    raw_connection Connection
}
func MakeTypedConnection[Receive, Send proto.Message](raw_connection Connection) TypedConnection[Receive, Send] {
    return TypedConnection[Receive, Send]{
        raw_connection: raw_connection,
    }
}
func (this *TypedConnection[Receive, Send]) Receive() (message Receive, err error) {
    var data Data
    data, err = this.raw_connection.Receive()
    if err == nil {
        var bytes []byte
        bytes, err = data.Bytes()
        if err == nil {
            message = new(Receive)
            err = proto.Unmarshal(bytes, message)
        }
    }
    return message, err
}

Error is on line message = new(Receive), since Receive is pointer I can not create pointer to *Receive using new(Receive) Is there anyway to overcome pointer type to create initialized pointer?

Usage of TypedConnection

stream := transfer.MakeTypedStream[*set.Request, *set.Response](raw_stream)

I tried to replace generic constraints from proto.Message to any, but in this case I won't be able to do proto.Unmarshal(bytes, message)

I was thinking of reflection and trying call new through it, but if it will success I will need to do casts, what I find really stupid when you have generics

I expect to find answer with something like new(*Receive)





How to get annotations of an Interface default method with reflection

I thought it would behave the same as with regular methods but I can't seem to find a way. For context, I have an interface that defines some default method implementations including parameters that are extended by some TestNG classes. If those classes are annotated at the class level with the @Test annotation it tries to execute those methods and fails when it tries to inject values. Seems like this is by design based on the responses I got here.

I was attempting the solution provided on that issue but I'm having no luck.

@Override
  @SneakyThrows
  public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
    // See: https://github.com/testng-team/testng/issues/2983
    return methods.stream()
        .filter(
            it -> {
              Method method = it.getMethod().getConstructorOrMethod().getMethod();
              return !method.isAnnotationPresent(Ignore.class) && !method.isDefault();
            })
        .collect(Collectors.toList());
  }

After annotating the Interface with the @Ignore annotation the ethods were not skipped. During debugging it was obvious it was getting empty array of annotations for the method.

I tried adding code as follows trying to get to the declaring class (the interface) and trying there without luck.

        List<IMethodInstance> newMethods= new ArrayList<>();
        for(IMethodInstance it:methods){
          Method method = it.getMethod()
              .getConstructorOrMethod()
              .getMethod();
          Method parentMethod = method.getDeclaringClass().getMethod(method.getName(),
     method.getParameterTypes());
          if(!parentMethod.isAnnotationPresent(Ignore.class)){
            newMethods.add(it);
          }else{
            log.info(String.format("Skipping method %s due to @Ignore annotation!",
     it.getMethod().getMethodName()));
          }
        }
        return newMethods;

AnnotationUtils.findAnnotation(method, Ignore.class) returns null even when the JavaDocs claim it includes interfaces.





mardi 26 septembre 2023

Creating a text type Shape inside a rectangle shape in Document in c# using Interop.VGCore

I am trying to automate a task of creating a rectangle with text inside it programmatically using Corel Draw type library. But because of very less documentation present it is getting really tough for me.

I have already added the reference to interop.VgCore , I am able to open a new document in the CorelDraw application as well

Type pia_type = Type.GetTypeFromProgID("CorelDRAW.Application");
Application app = Activator.CreateInstance(pia_type) as Application;
app.Visible = true;

I am not able to find what to do after this . I tried creating the instance of the Shape Class but , I can't do so getting some exception :

System.Runtime.InteropServices.COMException: 'Retrieving the COM class factory for component with CLSID {A77D0076-C6D1-4D32-9F72-F3A62CE56578} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).'





Automate a task of editing cdr files in c# using corel draw type library

I have nearly 200 cdr files with some shapes containing in it also I have a list of names. Shapes can be nested like rectangle inside rectangle.
I want to generate a new copy of that file with a name from the list in each of the group of shapes(text should be in innermost shape).
Then I have to save that file as svg.

here is what i have tried so far but I am not able to get a way what to do after this.

I used the Coreldraw type library and I am able to open the cdr file but I am not able to figure out which property of the document in corelDraw I should look to get the shapes.
previous questions also did not help me.

Type pia_type = Type.GetTypeFromProgID("CorelDRAW.Application");
            Application app = Activator.CreateInstance(pia_type) as Application;
            app.Visible = true;

            Document document = app.OpenDocument(@"Path_To_Cdr");




lundi 25 septembre 2023

Golang: Reflect returns different kind when same value depending on initialisation

Consider the following snippet of code:

// You can edit this code!
// Click here and start typing.
package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct{}

func main() {
    m := make(map[string]any)
    m["key"] = make([]*MyStruct, 0)
    myStructs := m["key"]
    myStructsVal := reflect.ValueOf(&myStructs)
    fmt.Println(myStructsVal.Type().Kind())
    fmt.Println(myStructsVal.Type().Elem().Kind())

    nm := make(map[string][]*MyStruct)
    nm["key"] = make([]*MyStruct, 0)
    nmStructs := nm["key"]
    nmStructsVal := reflect.ValueOf(&nmStructs)
    fmt.Println(nmStructsVal.Type().Kind())
    fmt.Println(nmStructsVal.Type().Elem().Kind())
}

The following the output:

ptr
interface
ptr
slice

This means that reflect considers the first myStructsVal to be a pointer to an interface and the second nmStructsVal to be a pointer to slice. Am I wrong when I consider the treatment of both variables to be same by the reflect library? Am I missing something?

Any help or pointers would be appreciated. Thanks!

Here is the Go playground link.





Access field in non public class through reflection

I am trying to access private field mRadialTimePickerModeButton in android.widget.TimePickerClockDelegate

TimePickerClockDelegate is a non public class extending TimePicker.AbstractTimePickerDelegate which implements TimePicker.TimePickerDelegate

I cannot make a new instance of this, I need to modify that field on this particular instance.

I tried accessing it like this:

Field field = TimePickerDialog.class.getDeclaredField("mTimePicker");
field.setAccessible(true);
TimePicker timePicker = (TimePicker) field.get(this);

Field delegateField = TimePicker.class.getDeclaredField("mDelegate");
delegateField.setAccessible(true);
Object delegate = delegateField.get(timePicker);

Field buttonField = delegate.getClass().getDeclaredField("mRadialTimePickerModeButton");
buttonField.setAccessible(true);
ImageButton radialTimePickerModeButton = (ImageButton) buttonField.get(delegate);

Getting: No field mRadialTimePickerModeButton in class Landroid/widget/TimePickerClockDelegate; (declaration of 'android.widget.TimePickerClockDelegate' appears in /system/framework/framework.jar!classes4.dex)





samedi 23 septembre 2023

Shallow Copy Function for Child Classes

In building a GOAP system, I have a parent Action class that hold most of the logic used for planning, while children classes inherit from it to provide a small amount of their own functionality, such as EatFoodAction.

During planning, I need to create a shallow copy of an Action to act as a node in my action graph, and I cannot for the life of me figure out how to write a Copy() function that can return a new instance of the child class, and not simply a new instance of the parent Action class.

It's not the copying fields that I can't do, it's the returning of a class of the right type.

This answer still requires overriding the copy function in each child class, something that I'd like to avoid.

A simple function to copy fields can only return the parent type, and I don't particularly want to create an override function for each child. A shallow copy will do just fine:

public class Action
{
    public Action Copy()
    {
        var newAction = new Action();
        // copy fields
        return newAction;
    }
}

The cloned action then gets passed into an ActionNode(Action action) class:

// planning code
var newNode = new ActionNode(oldAction.Copy())

I've tried generics, but they still need the exact type of the child class to work, and I'm not too sure how to use reflection without needing to the exact type to cast it to anyway.

How can I go about either returning the child class type, or is there some way to simply copy a class without needing to manually specify the exact type? Everything still inherits from the base Action class, so surely there is a way?

Thank you :)





vendredi 22 septembre 2023

Name of array of multidimensional arrays?

The name of an array of multidimensional arrays (or a multidimensional array of arrays) in .NET Reflection is in "reverse" order to what you would expect.

For example:

typeof(int[][,]).Name == "Int32[,][]" // "intuitively" it should be "Int32[][,]"
typeof(int[][,,][,]).Name == "Int32[,][,,][]" // seems it should be "Int32[][,,][,]" instead
typeof(int[][,,][]).Name == "Int32[][,,][]" // this is as I expected, but only because it's symmetrical

What is the reason for this?





List all available Functions in C

I want to create Bindings for another programming languge, and since there are hundrets of functions i wondering how i can make things more efficient by automating or so.

That means I want a list of all functions from a Header File with datatypes and return types like this:

void myfunction1(int)
void myfubction2()
void myfunction3(string, string)
....

I've imported the "glad.h" (header only lib) into my Main. Unfortunatly this library only binds system functions which means i cant extract them from the header file. Now I want to know if there is a C function which i can call in the Main which gives me exactly what i want, a list of all currently imported functions like described.

Is there a way to do so for example with relection or sth.

I tried to find out a soloution + I tried to give chatgpt a html list from the Docs, to extract the func names, but the list has no Definition () and returntype , that means i Would have klick hundreds of functions manually Copy them look what types and params they take ... and so on.





Best practice/ideas to invoke a methods based on network text commands? [closed]

I have a project in C# which includes controlling an external device - for example a motorized stage. I have a class which communicates with the stage and expose an API to control it / report its status.

I wish to have a server program that controls said stage, and can get text requests (json) over network, and based on the request content, activates the relevant method on the device class with the supplied parameters.

The requests are all async (i.e. client doesn't block/wait for an answer) and as such the communication is done via async messaging (RabbitMQ) and not on some RPC framework (such as gRPC).

I have managed to do it so far with reflection, for example:

public void MesseageReciveCallback(string msg)
{
    RemoteCommand cmd = json.Deserialized(msg);
    Type deviceType = _motorizedStage.GetType();
    deviceType.InvokeMember(cmd.Name, 
                            BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, 
                            null, 
                            _motorizedStage, 
                            cmd.Parameters);
}

but I was wondering if there is a better way of doing this in an elegant way under above conditions, other than just having a big old switch block that go over the cmd.Name parameter and calling the correct method.

I would mention that performance is not an issue - that is, I know reflection is not ideal in term of of it, but we are talking about research setup used by few users, handling few request per seconds at most.

My main gripe is the current solution make the client send all the parameters in a object[], making this setup more prone to runtime errors - i.e. if I changed the parameters type/order in some function on the MotorizedStage class, the client code won't alert me to it automatically at compilation time.

Thanks in advance for any ideas.





jeudi 21 septembre 2023

Why doesn't a method called with reflection have access to textBox?

I am new to c#. I am trying to use Reflection to execute a method in a string variable. This code will run without errors but only outpusts text to textBox1. What am I doing Wrong?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            xx();
        }

        private void xx()
        {
            Type type = typeof(Form1);
            System.Reflection.MethodInfo method = type.GetMethod("MyMethod");
            Form1 c = new Form1();
            string result = (string)method.Invoke(c, null);

            textBox1.Text = result;
        }


        public string MyMethod()
        {
            textBox2.Text = "Hello Text Box 2";
            return "Hello Text Box 1";
        }


type here




Map values from one struct to another struct by reflection

I am building simple system where KV struct represents Key, Value Pair of Property name and Value.

Model stuct has various simple types of Properties.

type Model struct {
    Id                         string    
    StringType                 *string
    BoolType                   *bool
    TimeType                   *time.Time
    FloatType                  *float64
    IntType                    *int
}

type KV struct {
    Fieldname       *string
    Oldvalue        *string
}

KV Struct parsing will contain following data

IntType 5
IntType nil
TimeType 2023-01-01
Id 4
BoolType nil
StringType test

Essentially need to build history of Model Object with whatever the property KV pair data available.

currentRow := Model{} //it can contain some values or empty struct or nil values
for j, a := range sysIdAudit {
    fact := currentRow
    la := a

    //reflect on fact
    ref := reflect.Indirect(reflect.ValueOf(&fact))
    fv := ref.FieldByName(strcase.ToCamel(*la.Fieldname))

    if !fv.IsValid() {
        continue
    }

    //v := reflect.ValueOf(a.Oldvalue)
    if la.Oldvalue == nil {
        fv.Set(reflect.Zero(fv.Type()))
    } else {

        switch fv.Elem().Type().Name() {
        case "int64":
            i, _ := strconv.ParseInt(*la.Oldvalue, 10, 64)
            reflect.Indirect(fv).SetInt(i)
            break
        case "float64":
            f, _ := strconv.ParseFloat(*la.Oldvalue, 8)
            reflect.Indirect(fv).SetFloat(f)
            break
        case "string":
            reflect.Indirect(fv).SetString(*la.Oldvalue)
            break
        case "bool":
            b, _ := strconv.ParseBool(*la.Oldvalue)
            reflect.Indirect(fv).SetBool(b)
            break
        case "Time":
            t, _ := time.Parse("2006-01-02 15:04", *la.Oldvalue)
            reflect.Indirect(fv).Set(reflect.ValueOf(t))
            break
        default:
            fv.Set(fv)
            break
        }

    }

    history = append(history, fact)
    currentRow = fact
}

I am running into multiple panics (basically strugulling to understand reflection properly and use it)

panic: reflect: call of reflect.Value.Type on zero Value -> on this line switch fv.Elem().Type().Name()





mercredi 20 septembre 2023

How can I get the MethodInfo of Expression.Lambda

I'm trying to get the MethodInfo of the static Expression.Lambda<TDelegate>(Expression, ParameterExpression[]) method. But I'm getting an AmbiguousMatchException when I try with GetMetod:

MethodInfo lambda = typeof(Expression).GetMethod(nameof(Expression.Lambda), new[] { typeof(Expression), typeof(ParameterExpression[]) });

I have figured out a very convoluted way by getting all public static methods and filtering:

MethodInfo lambda = (
    from m in typeof(Expression).GetMethods(BindingFlags.Public | BindingFlags.Static)
    let p = ((MethodBase)m.ReturnParameter.Member).GetParameters()
    where m.Name == nameof(Expression.Lambda) && m.ReturnType.IsGenericType 
                                              && p.Length == 2 
                                              && p[0].ParameterType == typeof(Expression) 
                                              && p[1].ParameterType == typeof(ParameterExpression[])
    select m
).Single();

It works but seems overly complicated and pretty dangerous (cast to MethodBase plus Single() call).

Is there a simpler solution to get that generic MethodInfo?





mardi 19 septembre 2023

`MethodHandle` slower than Reflection when accessing Object

I would like to call a method via reflection in the most performant way possible.

The method returns an Object.

I've implemented this using both reflection and MethodHandles, I was expecting MethodHandle to be faster - but that's not what I'm seeing (~20-40% slower).

Take the following JMH benchmark:

import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 200, time = 10, timeUnit = TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class AccessorBenchmark {
    private static final Object[] EMPTY_ARGS = new Object[0];

    private POJO source;
    private Method method;
    private MethodHandle methodHandle;
    private MethodHandle methodHandleModifiedReturnType;

    @Setup
    public void setup() throws ReflectiveOperationException {
        source = new POJO();

        method = source.getClass().getDeclaredMethod("getNumber");
        
        methodHandle = MethodHandles.lookup().unreflect(method);
        methodHandleModifiedReturnType = methodHandle.asType(methodHandle.type().changeReturnType(Number.class));
    }

    @Benchmark
    public Number reflection() throws Throwable {
        return (Number) method.invoke(source, EMPTY_ARGS);
    }

    @Benchmark
    public Number methodHandle() throws Throwable {
        return (Number) methodHandle.invoke(source);
    }

    @Benchmark
    public Number methodHandleInvokeExact() throws Throwable {
        return  (Number) methodHandleModifiedReturnType.invokeExact(source);
    }

    public class POJO {
        private final AtomicInteger counter = new AtomicInteger();

        public AtomicInteger getNumber() {
            return counter;
        }
    }
}

The following result is returned with Java 17:

Benchmark                                     Mode   Cnt   Score    Error   Units
AccessorBenchmark.methodHandle                avgt  1000   2.856 ±  0.004   ns/op
AccessorBenchmark.methodHandleInvokeExact     avgt  1000   2.359 ±  0.003   ns/op
AccessorBenchmark.reflection                  avgt  1000   2.017 ±  0.002   ns/op

Any ideas?





lundi 18 septembre 2023

Hot-patching "deps.json" at runtime?

I have a .NET 6.0 DLL that contains an Entity Framework Core DbContext to a SQL Server database.

If that assembly is referenced by the .NET 6.0 EXE and then called, everything works just fine.

However, if I try to use it in a plug-in concept and load the DLL via reflection like this:

var assembly = Assembly.LoadFrom("Plugin.dll");
var pluginType = assembly.GetExportedTypes()
  .Where(t => t.IsAssignableTo(typeof(IPlugin)))
  .First();
var plugin = (IPlugin)Activator.CreateInstance(pluginType);

Then I get

Microsoft.Data.SqlClient is not supported on this platform.

And the only difference is in the PluginHost.deps.json that now has no clue that at some point Microsoft.Data.SqlClient may get involved.

PluginHost.deps.json

And I was wondering if there was some hot-load function to teach the EXE the dependencies of the DLL.

The whole test endeavor can be found on GitHub





How to invoke a static abstract method by reflection? [duplicate]

I'm trying to invoke a static abstract method by reflection. Declaring static abstract methods on interfaces is a preview feature about which you can read more here.

When invoking a non-static abstract method one can simply call TheType.GetMethod("MethodName").Invoke(null, null) and the method is invoked, but when declaring a static abstract method in a inherited interface, it doesn't seem to become a public static method in the inheriting type. An example:

I have an interface Entity declaring a static abstract method GetTableName():


public interface Entity
{
    public static abstract string GetTableName();
}

Then there are multiple types of Entities that inherit from the Entity interface and implement the GetTableName method:


static string Entity.GetTableName() => "[dbo].[SomeTable]";

When trying to add the public keyword to this implementation, an error message is given: The modifier 'public' is not valid for explicit interface implementation, which I interpret as: the interface has already declared this method as public, so remove this keyword. (Is this correct?)

When trying to invoke the static abstract method with reflection on the implementing type, the method is not found and GetMethod() returns null. During debugging, I can see that the method is declared as the full qualifier of the Entity type, followed by the method name 'GetTableName', so I have tried to invoke in multiple ways such as:


var tableName = someType.GetMethod("GetTableName").Invoke(null, null);
var tableName = someType.GetMethod("FullQualifier.Entity.GetTableName").Invoke(null, null);
var tableName = someType.GetMethod("GetTableName", BindingFlags.NonPublic).Invoke(null, null);
var tableName = someType.GetMethod("GetTableName", BindingFlags.Static).Invoke(null, null);

Sadly, all return null. Upon further debugging, the method seems to be declared as NonPublic. Still, using the NonPublic binding flag has no effect. How can one invoke the static abstract method with reflection? Any help would be much appreciated.





samedi 16 septembre 2023

C# Reflection and overloaded Methods: Get Method the compiler would have chosen / "Closest Ancestor"

Given this Situation:

class Wrapper {
   class Base {}
   class A : Base {}
   interface IA {}
   class B : A, IA {}

   void Func(Base param) {}
   void Func(A param) {}
   void Code() 
   {
      var param = new B();
      Func(param); //the compiler picks the "best polymorphism match" or maybe "closest ancestor", which is Func(A param)
   }
}

I don't actually know how the compiler picks the method. I assume it's the "closest ancestor", but I'm aware that this definition has problems itself - When a void Func(IA param) { } is added to the code above, the call Func(param); becomes a compile error CS0121 The call is ambiguous between the following methods or properties: 'Wrapper.Func(A)' and 'Wrapper.Func(IA)'

With Reflection, how would I go about to find the same Func the compiler would have chosen if the Type information had been available at compile time? typeof([Func-param]).IsAssignableFrom(typeof(B)) is true for both function params. typeof(B).IsSubclassOf([Func-param]) is also true for both functions.





vendredi 15 septembre 2023

Creating a Generic Registration Component in Angular for Any Model

I'm trying to create a generic registration component in Angular that can handle registration forms for various models. The idea is to have a single component, let's call it RegistrationComponent, that can dynamically generate HTML input fields based on the properties of the model it receives.

For instance, I have two classes Product and SalesRepresentative as follows:

export class Product implements Persistable { 
  id!: number;
  code!: string;
  name!: string;
  purchasePrice!: number;
  brand!: string;
  manufacturer!: string;
}

export class SalesRepresentative implements Persistable {
  id!: number;
  personalData!: PersonalData;
}

And I want to use the RegistrationComponent to generate registration forms for both of these classes. Here's the HTML structure that I want to generate for the Product class as an example:

 <div class="col-md-12">
  <div class="card card-user">
    <div class="card-header">
    </div>
    <div class="card-body">
      <form (ngSubmit)="submitForm()">
        <!-- Dynamically generated input fields based on Product properties -->
        <div class="row">
          <!-- Input field for code -->
          <div class="col-md-4 pr-1">
            <div class="form-group">
              <label>Code:</label>
              <input type="text" class="form-control" placeholder="Code" [(ngModel)]="product.code" name="code">
            </div>
          </div>
          <!-- Input field for name -->
          <div class="col-md-5 px-1">
            <div class="form-group">
              <label>Name:</label>
              <input type="text" class="form-control" placeholder="Name" [(ngModel)]="product.name" name="name">
            </div>
          </div>
          <!-- Input field for purchasePrice -->
          <div class="col-md-3 pl-1">
            <div class="form-group">
              <label for="purchasePrice">Purchase Price:</label>
              <input type="text" class="form-control" placeholder="Purchase Price" id="purchasePrice" [(ngModel)]="product.purchasePrice" name="purchasePrice" appRealMask>
            </div>
          </div>  
        </div>
        <!-- Additional input fields for Product properties -->
        <div class="row justify-content-around">
          <!-- Input field for brand -->
          <div class="col-md-5 pr-1">
            <div class="form-group">
              <label for="brand">Brand:</label>
              <input type="text" class="form-control" placeholder="Brand" id="brand" [(ngModel)]="product.brand" name="brand">
            </div>
          </div>    
          <!-- Input field for manufacturer -->
          <div class="col-md-5 px-1">
            <div class="form-group">
              <label for="manufacturer">Manufacturer:</label>
              <input type="text" class="form-control" placeholder="Manufacturer" id="manufacturer" [(ngModel)]="product.manufacturer" name="manufacturer">
            </div>
          </div>        
        </div>
        <!-- Submit button -->
        <div class="row text-center">
          <div class="col-md-12 pr-1 px-1">
            <div class="update ml-auto mr-auto">
              <button type="submit" class="btn btn-outline-secondary">Save Data</button>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>




How do I access the underlying struct of a reflect.Value?

How do I access the underlying (opaque) struct of a reflect.Value (eg, a time.Time) from the reflection library?

So far, I've been creating a temporary time.Time, taking the ValueOf it, then using Set() to copy it out. Is there a way to access the original directly as a time.Time?





Check @Override annotation presence on method

I have a java.lang.reflect.Method method and I want to check if it is marked with @Override annotation.

Was trying to do that with method.isAnnotationPresent(Override.class) but this approach doesn't applicable for this annotation. Also tried MergedAnnotations.from(method).isPresent() but it also doesn't return true for my method with @Override.

Is it possible to check that?





jeudi 14 septembre 2023

Crash Caused by: java.util.ServiceConfigurationError

Hello I have a problem when I call method.invoke() I have a crash Caused by: java.util.ServiceConfigurationError: org.slf4j.spi.SLF4JServiceProvider: org.apache.logging.slf4j.SLF4JServiceProvider not a subtype. The strange thing is that when I use java classes, the functions all work fine, but when others the error that I posted above occurs, but I want to point out that classes methods and functions that increase java classes work fine. Here is the code for method.invoke()

for (Method method : clazz.getDeclaredMethods()){
    try {
        method.setAccessible(true);
        method.invoke(clazz.getDeclaredConstructor().newInstance());
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
@SubscribeEvent
public static void test() {
    System.out.print(SomeClass.someFunction());
}

I used ChatGpt but it didn't help me.





mercredi 13 septembre 2023

Is there a way to find all models that contain a GenericRelation to a particular model in Django?

Lets say we have the following model with a GenericForeignKey

class Comment(models.Model):
    customer_visible = models.BooleanField(default=False)
    comment = models.TextField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    model = GenericForeignKey()

And in several places it is referenced in other models:

class Invoice(models.Model):
    ...
    comments = GenericRelation(Comment)
...
class Contract(models.Model):
    ...
    comments = GenericRelation(Comment)

Is it possible to get a list of the types that reference the Comment model? e.g. [Contract,Invoice] in this example?

Similar functionality is possible in for instance C# with Reflection.

I need something that will work when there are no references already, so Comment.objects.values('content_type') won't work.





How SetValue to TimeSpan Property with Reflection c#?

I have the following problem:

I'm trying to Set a value of a TimeSpan property with reflection but the property reflect as Int64 Ticks with SetMethod null and when I try to make (PropertyInfo).SetValue(...,...) I get a "property set method not found" Exception.

So my question is:

How Can I Set a TimeSpan value of a property by Reflection?

I'm using following code that works for all properties with exception of TimeSpan

private static void PropSetValue(PropertyInfo prop, PropertyInfo updaterProp, object updater, object toUpdate)
{
    var propValue = prop.GetValue(toUpdate, null);
    var updValue = updaterProp.GetValue(updater, null);

    if (!Equals(propValue, updValue))
        prop.SetValue(toUpdate, updValue, null);
}

Thankyou in advance for suggestions or workarounds.

Piercarlo





Trying to override the font size of label of the TextInputLayout, using reflection

I'm trying to change the font size of the label / hint of TextInputLayout. As it has a property collapsingTextHelper where it holds all data related to font of label / hint, accessing it, would solve the problem. But it's private. So I'm trying to use reflect.

Relavent code:

Field field = TextInputLayout.class.getDeclaredField("collapsingTextHelper");
                field.setAccessible(true);
                Object collapsingTextHelper = field.get(this);

                Field expandedTextSizeField = collapsingTextHelper.getClass().getDeclaredField("expandedTextSize");
                Field collapsedTextSizeField = collapsingTextHelper.getClass().getDeclaredField("collapsedTextSize");

                expandedTextSizeField.setAccessible(true);
                expandedTextSizeField.setFloat(collapsingTextHelper, mainHintTextSize);
                collapsedTextSizeField.setAccessible(true);
                collapsedTextSizeField.setFloat(collapsingTextHelper, mainHintTextSize);

Here is my full code:


public class CustomTextInputLayout extends TextInputLayout {
    private final float mainHintTextSize = 24;

    public CustomTextInputLayout(@NonNull Context context) {
        super(context);
    }

    public CustomTextInputLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomTextInputLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextInputLayout);
//        mainHintTextSize = a.getDimensionPixelSize(R.styleable.CustomTextInputLayout_mainHintTextSize, 0);
        a.recycle();
    }

    @Override
    public void addView(@NonNull View child, int index, @NonNull ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        if (child instanceof EditText) {
            try {
                Field field = TextInputLayout.class.getDeclaredField("collapsingTextHelper");
                field.setAccessible(true);
                Object collapsingTextHelper = field.get(this);

                Field expandedTextSizeField = collapsingTextHelper.getClass().getDeclaredField("expandedTextSize");
                Field collapsedTextSizeField = collapsingTextHelper.getClass().getDeclaredField("collapsedTextSize");

                expandedTextSizeField.setAccessible(true);
                expandedTextSizeField.setFloat(collapsingTextHelper, mainHintTextSize);
                collapsedTextSizeField.setAccessible(true);
                collapsedTextSizeField.setFloat(collapsingTextHelper, mainHintTextSize);

            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public float getMainHintTextSize() {
        return mainHintTextSize;
    }

    public void setMainHintTextSize(float size) {
        if (getEditText() != null) {
            throw new IllegalStateException("Hint text size must be set before EditText is added");
        }

//        mainHintTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, getResources().getDisplayMetrics());
    }
}

And it doesn't raise any error.

But even the code has been executed, it doesn't change the font size of the collapsed text.





MethodHandle cannot be cracked when using LambdaMetafactory?

I want to convert a Record's constructor to a Function<Object[], T> using lambdametafactory (T is a generic type), here are my codes:

public record R(
        String a,
        String b
) {
}

private static void testRecord() throws Throwable {
    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodHandle constructor = lookup.findConstructor(R.class, MethodType.methodType(void.class, String.class, String.class));
    constructor = constructor.asSpreader(Object[].class, 2);
    R r = (R) constructor.invokeExact(new Object[]{"a", "b"});
    System.out.println(r.a());
    System.out.println(r.b());
    MethodType methodType = constructor.type();
    CallSite callSite = LambdaMetafactory.metafactory(lookup,
            "apply",
            MethodType.methodType(Function.class),
            methodType.erase(),
            constructor,
            methodType);
    Function<Object[], R> f = (Function<Object[], R>) callSite.getTarget().invokeExact();
    R apply = f.apply(new Object[]{"a", "b"});
    System.out.println(apply.a());
    System.out.println(apply.b());
} 

When using constructor.invokeExact() method, the record could be instantiated successfully, but the CallSite couldn't be generated by LambdaMetafactory.metafactory() method because of following errors:

Exception in thread "main" java.lang.invoke.LambdaConversionException: MethodHandle(Object[])R is not direct or cannot be cracked
    at java.base/java.lang.invoke.AbstractValidatingLambdaMetafactory.<init>(AbstractValidatingLambdaMetafactory.java:143)
    at java.base/java.lang.invoke.InnerClassLambdaMetafactory.<init>(InnerClassLambdaMetafactory.java:168)
    at java.base/java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:336)

How can I fix this?





vendredi 8 septembre 2023

Replace Generic Types In `System.Type[]` With Types

Say one has a generic definition MethodInfo object, that is, a MethodInfo object such that methodInfo.IsGenericMethodDefinition == true:

MethodInfo methodInfo = somethingCool;

Say also that they also have a list of generic arguments:

Type[] genericArguments = somethingElseAlsoCool;

I can get the types of the parameters of the method with:

Type[] types = (
    from ParameterInfo parameter
    in methodInfo.GetParameters()
    select parameter.ParameterType
    ).ToArray();

Now, I can fill in the generic arguments to methodInfo with methodInfo.MakeGenericMethod:

MethodInfo invokableMethodInfo = methodInfo.MakeGenericMethod(genericArguments);

However, what about the array of Types? I can just prematurely increment though the types as such:

for (int i = 0; i < types.Length; i++)
    types[i] = types[i].MakeGenericType(genericArguments);

But this wouldn't make sense. Consider the following method:

void MyGenericMethod<TOne, TTwo, TThree>(IDictionary<TOne, TThree> Dictionary);

If I did the previously mentioned algorithm, then the types would map incorrectly:

TOne   => TKey   //Fine, but only by coincidence.
TTwo   => TValue //Incorrect. TValue should be TThree, not TTwo.
TThree => ?      //What is this?

I'm stumped. How can I define the undefined generics in my array of types?

Any help would be greatly appreciated!





problems with cross field custom validation in go

I'm trying to learn golang custom validation but running into a lot of trouble. Here's the code for what I've been attempting:

package main
import (
        "reflect"
        "github.com/go-playground/validator/v10"
        "fmt"
)
type TeamMember struct {
        Country string
        Age int
        DropShip bool `validate:"is_eligible"`
}
func CustomValidation(fl validator.FieldLevel) bool {
  /*
    if(DropShip == true) {
       httpresponse = curl https://3rd-party-api.com/?country=<Country>&age=<Age>
       return httpresponse.code == 200
    }
    return false
  */

  b := fl.Parent()
  fmt.Println(reflect.TypeOf(b))
  fmt.Println(reflect.ValueOf(b))
  c := reflect.ValueOf(b).Interface()
  fmt.Println(c.(TeamMember))
  fmt.Println("============")
  return true
}


func main() {
  var validate *validator.Validate
  validate = validator.New(validator.WithRequiredStructEnabled())
  _ = validate.RegisterValidation("is_eligible", CustomValidation)
  teammember := TeamMember{"Canada", 34, true}

  validate.Struct(teammember)
}

You can see the validation logic that I'm attempting in the code comments...If the DropShip field is true, then I need to submit the Country and Age to another API to see if this team member is eligible.

The problem is that I'm struggling with the reflect library to access the Country and Age fields in the TeamMember struct. The fmt.Println(c.(TeamMember)) line crashes my program.

Can someone give me an example of how to access the other TeamMember fields? Or is my approach to validation in violation of the idiomatic way of validating in golang?





Creating and saving relationships taking too much time in Neo4J using Spring Data

I'm trying to migrate JSON documents from Couchbase into Neo4j. After receiving the document, I find out the type of object to create by reading the some fields. Each node object class inherits some node properties like ID, labels and Version(for optimistic locking) from the Transaction class.

Example of a node class:

@Node
public class User extends Transaction{

    public static final String featureID = "12109";

    public static final String featureVariantID = "000";

    @Property("FullName")
    private String fullName;

    @Property(name = "Alias")
    private String alias;

    @Property(name = "EmploymentType")
    private String employmentType;

    @Property(name = "EmployeeCode")
    private String employeeCode;

    @Relationship("LineManager")
    Set<RelatedTo<User>> lineManagers;

    @Relationship("FunctionalManager")
    Set<RelatedTo<User>> functionalManagers;

    @Relationship("LegalEntity")
    Set<RelatedTo<LegalEntity>> legalEntities;

    // More relations like these

    

    public User() {

    }

    public User(String transactionID, String tenantID) {
        super(featureID, featureVariantID, transactionID, tenantID);
        this.fullName = "";
        this.alias = "";
        this.employmentType = "";
        this.employeeCode = "";
        lineManagers = new LinkedHashSet<>();
        functionalManagers = new LinkedHashSet<>();
        legalEntities = new LinkedHashSet<>();
        // ....
    }
    
    //Getters and Setters

    // Used to get which fields of the JSON document are to be used to populate the relationship sets
    private static final Map<String, String> allowedRelationships = new HashMap<>();
    static {
        allowedRelationships.put("LineManager", "Data.LineManagerUserID");
        allowedRelationships.put("FunctionalManager", "Data.FunctionalManagerUserID");
        allowedRelationships.put("LegalEntity", "Data.EmployeeLegalEntityID");
        
    }

    public Map<String, String> getAllowedRelationships() {
        return User.allowedRelationships;
    }

}

Other than this there are 12 other classes that have a similar structure.
The structure of the relationship entity is:

@RelationshipProperties
public class RelatedTo<T extends Transaction> extends BaseRelationship <T>{

    @Property("DocumentID")
    private String documentID;

    public RelatedTo() {

    }

    public RelatedTo(String effectiveFromTimestamp, String effectiveTillTimestamp, String status, T target, String documentID) {
        super(effectiveTillTimestamp, effectiveFromTimestamp, status, target);
        this.documentID = documentID;
    }

    //Getter and Setter
}

It inherits from the parent class:

@RelationshipProperties
public class BaseRelationship <Target extends Transaction>{

    @Id
    @GeneratedValue
    private Long id;

    @Property("EffectiveTillTimestamp")
    private String effectiveTillTimestamp;

    @Property("EffectiveFromTimestamp")
    private String effectiveFromTimestamp;

    @Property("Status")
    private String status;

    @TargetNode
    private Target targetNode;

    public BaseRelationship(String effectiveTillTimestamp, String effectiveFromTimestamp, String status, Target targetNode) {
        this.effectiveTillTimestamp = effectiveTillTimestamp;
        this.effectiveFromTimestamp = effectiveFromTimestamp;
        this.status = status;
        this.targetNode = targetNode;
    }

    public BaseRelationship() {
    }

    // Getters and Setters
}

To determine the type of object to create I'm making use of Reflection which returns a

<T extends Transaction> Class<T>

object. Then I create and save the node into Neo4j. After that I read the document again to create relationships for that node along with some processing of data after which I save the node. Like:

{
    LegalEntity parentNode = transactionRepository.getOrCreateNode(transactionMap, tenantID, relTransactionID, LegalEntity.class);// fetching node from database
                RelatedTo<LegalEntity> newParentRelationship = new RelatedTo<>(effectiveFromTimestamp, effectiveTillTimestamp, status, parentNode, documentID);
                Set<RelatedTo<LegalEntity>> existingRelationships = user.getLegalEntities();
    // some processing of data and then updating the above set
}

The problem is that each save is taking 4-10 seconds including the processing, fetching and saving. Each node can contain 10-15 relations. That means each relation is taking more than 400 ms to be created.

Is there some way to improve the speed, as I have to import more than 50,000 documents from couchbase.

Currently I'm updating each node and relation in a single thread. I've tried to do it using an ExecutorService, but the save operations would become stuck in a deadlock and throw either an Optimistic Locking Exception or Transient Data Access Exception.





How to apply a decorator to existing class

I have class A in external package

class A {
  mess: string;
}

And my method Decorator

function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  target.propertyKey = 'test';
};

I want to apply my decorator test to class A, but I can't get reflection of class A to apply

test(reflectionOfClassA, attributeKey)

How do I get reflection of class A? I can't update code of class A, because it is imported from other package





jeudi 7 septembre 2023

WrongMethodTypeException with MethodHandle.invokeExact() but no arguments and return type is same

I'm using Java 17 on AWS Lambda. I have an interface Foo with a method bar(), returning a CompletableFuture<Map<Bar, Long>>:

public interface Foo {
  public CompletableFuture<Map<Bar, Long>> bar();
}

In the MyProcessor class, I have an instance reference to an implemention of Foo which is FooImpl:

class MyProcessor {

  private final Foo foo;

  MyProcessor() {
    foo = goGetFooImpl();
  }

  void doSomething() {
    …
  }

}

Finally in MyProcessor.doSomething(), I look up the Foo.bar() method and try to invoke it using a method handle (leaving out exception handling for clarity):

  //filter out the only method with the name "bar"
  Method barMethod = foo.getClass().getDeclaredMethods().…;
  MethodHandle = MethodHandles.lookup().unreflect(barMethod);
  CompletableFuture<?> result = (CompletableFuture<?>)methodHandle.invokeExact(foo);

The error message is odd:

java.lang.invoke.WrongMethodTypeException: expected (FooImpl)CompletableFuture but found (Foo)CompletableFuture

I realize with MethodHandle.invokeExact() that the arguments and return type must be exact. In this case there are no arguments. And it is my understanding that the generic type of CompletableFuture is erased at runtime; thus in this case the concrete return type is the same. So what is the problem?

What does the error message mean when it mentions (Fooimpl) and (Foo)? How does the type of the target impact the type of CompletableFuture?

I realize that the bar() method is declared on Foo, but looked up that method on the class of an instance of FooImpl. But why would that be a problem? From the documentation I had understood that MethodHandle.invokeExact() works on virtual methods.

I can call methodHandle.invoke(foo) here and it works fine, but not methodHandle.invokeExact(foo). What is not "exact" about what I'm doing? Does anyone know what the error message means?

I found MethodHandle cast return type which appears to be related, but I'm still not getting it. A CompletableFuture is a CompletableFuture. Since when is there such things as (Foo)CompletableFuture and (FooImpl)CompletableFuture and why would they be different?





Invoke a method using reflection

I am trying to connect to and subscribe to Topics on ROSbridge using the ros-sharp project. It works fine if i specify the Type of message upon subscribing as per the code example in the Test Client:

rosSocket = new RosSocket(new RosBridgeClient.Protocols.WebSocketNetProtocol(uri), RosSocket.SerializerEnum.Newtonsoft_JSON);
string subscription_id = rosSocket.Subscribe<JointState>("/joint_states", SubscriptionHandler);

Where this is the Subscribe method:

public string Subscribe<T>(string topic, SubscriptionHandler<T> subscriptionHandler, int throttle_rate = 0, int queue_length = 1, int fragment_size = int.MaxValue, string compression = "none") where T : Message
{
string id;
lock (SubscriberLock)
{
id = GetUnusedCounterID(Subscribers, topic);
Subscription subscription;
Subscribers.Add(id, new Subscriber<T>(id, topic, subscriptionHandler, out subscription, throttle_rate, queue_length, fragment_size, compression));
Send(subscription);
}
return id;
}

And the Subscription Handler is as follows:

private static void SubscriptionHandler(object message)
{
    string msg = JsonConvert.SerializeObject((Message)message, Formatting.None);
    Console.WriteLine(msg);
}

however I wish to be able to specify the topic and message type by string and find that type and call the subscribe method.

I know I can do it with an exhaustive Switch e.g.:

public static string SubscribeSwitch(string type, string topic) 
{
switch (type)
{
case "sensor_msgs/JointState":
    return rosSocket.Subscribe<JointState>(topic, SubscriptionHandler);
    break;
case "actionlib_msgs/GoalID":
    return rosSocket.Subscribe<GoalID>(topic, SubscriptionHandler);
    break;
}
return "";
}

But this will get pretty long and unmanageable especially if i add new Message types for different robots. I have therefore spent some time trying to use reflection to get the type to invoke the Subscribe call, but I seem to be falling over when trying to pass in the Subscription handler which has a non generic delegate type. Has anyone done similar, or provide an example of how to do this - many thanks. The following code for exmaple falls over at var subscribe: InvalidCastException: Unable to cast object of type 'System.RuntimeType' to type 'RosSharp.RosBridgeClient.Message'.

Type msgType = Type.GetType("RosSharp.RosBridgeClient.MessageTypes.Sensor.JointState,RosBridgeClient");

var mi = typeof(RosSocket).GetMethod("Subscribe");

Type[] aparams = new Type[1];
aparams[0] = msgType;
var fooRef = mi.MakeGenericMethod(aparams);

object[] test2 = new object[1];
test2[0] = msgType;

object[] test = new object[6];
test[0] = "/joint_states";

// get subscribe method info
var subscribe = typeof(RosSocketConsole).GetMethod(nameof(SubscriptionHandler), BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, test2);

test[1] = subscribe;
test[2] = 0;
test[3] = 1;
test[4] = int.MaxValue;
test[5] = "none";
string subscription_id = (string)fooRef.Invoke(rosSocket, test);

Thanks for any assistance





Unit Test Cases for Hive Custom UDFs by mocking Java Reflection calls

I have a requirement where I need to develop Hive Custom UDFs that uses Java reflection API to make calls to external classes.

Since I'm new to Java Reflection, I have dedicated some time learning it and was able to do a basic implementation.

But I'm facing issues while writing unit test cases for this implementation as I'm facing some challenges in mocking Reflection APIs.

Below is the example for Hive Custom UDF.

ReverseString.java

package com.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReverseString extends GenericUDF {

    private StringObjectInspector input;
    Class<?> c = null;
    Object ob = null;


    @Override
    public ObjectInspector initialize(ObjectInspector[] arg0) throws UDFArgumentException {

        // check to make sure the input has 1 argument
        if (arg0.length != 1) {
            throw new UDFArgumentException("input must have length 1");
        }

        // create an ObjectInspector for the input
        ObjectInspector input = arg0[0];

        // check to make sure the input is a string
        if (!(input instanceof StringObjectInspector)) {
            throw new UDFArgumentException("input must be a string");
        }


        this.input = (StringObjectInspector) input;
        System.out.println("Success. Input formatted correctly");

        return init(arg0);
    }

    public ObjectInspector init(ObjectInspector[] arg0) throws UDFArgumentException {

        try {
            c = Class.forName("com.hive.inherit.DummyUdf");
            ob = c.getConstructor().newInstance();
            Method method = c.getMethod("print", String.class);
            String res = (String) method.invoke(ob, "Test");
            System.out.println("RES: "+res);

        } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }

        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }


    @Override
    public Object evaluate(DeferredObject[] arg0) throws HiveException {

        if (input == null || arg0.length != 1 || arg0[0].get() == null) {
            return null;
        }
        String forwards = input.getPrimitiveJavaObject(arg0[0].get()).toString();

        return reverse(forwards);
    }


    public  String reverse(String in) {
        String res = null ;
        try {
            Method method = this.c.getMethod("reverse",String.class);
            res = (String) method.invoke(this.ob, in);
        } catch (  NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return res;
    }

    @Override
    public String getDisplayString(String[] strings) {
        return "reverses string";
    }
}

Below is the class that is being called by Reflection.

DummyUdf.java

package com.hive.inherit;

public class DummyUdf {
    

    public DummyUdf(){
        System.out.println("DummyUdf");
    }

    public String print(String str){
        System.out.println("DummyUdf-str:"+str);
        return str;
    }

    public String reverse(String in) {

        int l = in.length();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < l; i++) {
            sb.append(in.charAt(l - i - 1));
        }
        return sb.toString();
    }
}

The unit test cases that I'm trying to implement,

ReverseStringTest.class



@RunWith(MockitoJUnitRunner.class)
public class ReverseStringTest {

    @Test
    public void testSimpleString() throws HiveException {

        //ReverseString r = Mockito.spy(new ReverseString());
        ReverseString r = mock(ReverseString.class);
        ObjectInspector input = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
        when(r.init(Mockito.any())).thenReturn(input);
        JavaStringObjectInspector resultInspector = (JavaStringObjectInspector) r.initialize(
                new ObjectInspector[] { input });
        Text forwards = new Text("hello");
        when(r.reverse(Mockito.any())).thenReturn("olleh");
        Object result = r.evaluate(new GenericUDF.DeferredObject[] { new GenericUDF.DeferredJavaObject(forwards) });
        System.out.println(result);
        assertEquals("olleh", resultInspector.getPrimitiveJavaObject(result));
    }
}

The test case is failing with NullPointerException.

java.lang.NullPointerException at com.hive.udf.ReverseStringTest.testSimpleString(ReverseStringTest.java:34) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)

Can someone please suggest on how to mock the reflection calls appropriately?

Thanks in advance.





lundi 4 septembre 2023

Field exists but NoSuchFieldException

I have simple code where I try to get the signature of a field:

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {

    static class Test {
        int hi =  1;
    }

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException {
        Field hi = Test.class.getDeclaredField("hi");

        Field field = Field.class.getDeclaredField("signature");
        field.setAccessible(true);
        String signature = (String) field.get(hi);

        System.out.println(signature);
    }
}

however, I am getting this exception:

Exception in thread "main" java.lang.NoSuchFieldException: signature
    at java.base/java.lang.Class.getDeclaredField(Class.java:2663)
    at Main.main(Main.java:13)




samedi 2 septembre 2023

Method and/or KFunction to KSFunctionDeclaration

What is the most reliable way of getting KSFunctionDeclaration(from kotlin source processor framework) instance from Method/KFunction instances? Specially if there is several overloads, and I need to get exactly one that matches by signature.





vendredi 1 septembre 2023

Check if KFunction<*> is an extension function/instance function/object function/top level function?

How I can check if KFunction is one of mentioned function types?





How to determine if struct property has `nil` value using reflection in Go?

I am creating an app in Go that is supposed to receive a JSON and unmarshal it into different possible values.

To do this, I created a parent struct, that contains the possible JSON formats that the app will receive.

So the idea is to try to unmarshal the received JSON into each child struct and check if any of them didn't receive any values. If this is the case, then the app will set that struct to nil at a later point.

The problem is that when I try to use the isNil() method from Go's reflection, it doesn't work for a generic struct. It only works if I know the struct's format.

Here is an example (playground link):

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type User struct {
    Username *string `json:"username,omitempty" required:"true"`
    Password *string `json:"password,omitempty" required:"false"`
}

type UserError struct {
    Error *string `json:"error,omitempty" required:"true"`
    Code  *int    `json:"code,omitempty" required:"true"`
}

type UserOrError struct {
    User      *User
    UserError *UserError
}

var userJson = `{ "username": "john@email.com", "password": "password" }`

func main() {
    user := &UserOrError{}
    data := []byte(userJson)

    types := reflect.TypeOf(user).Elem()
    values := reflect.ValueOf(user).Elem()

    for i := 0; i < types.NumField(); i++ {
        fieldType := types.Field(i)
        unmarshalledValue := reflect.New(fieldType.Type)

        err := json.Unmarshal(data, unmarshalledValue.Interface())
        if err != nil {
            panic(err)
        }

        value := unmarshalledValue.Elem()
        fmt.Printf("Unmarshalled: %+v - hasValues: %v \n", value, hasValues(value))
        // Unmarshalled: &{Username:0x14000102110 Password:0x14000102120} - hasValues: true
        // Unmarshalled: &{Error:<nil> Code:<nil>} - hasValues: true
        values.Field(i).Set(value)
    }

    fmt.Printf("User: %+v - hasValues: %v\n", user.User, hasValues(user.User))
    // User: &{Username:0x14000102110 Password:0x14000102120} - hasValues: true
    fmt.Printf("UserError: %+v - hasValues: %v\n", user.UserError, hasValues(user.UserError))
    // UserError: &{Error:<nil> Code:<nil>} - hasValues: false
}

func hasValues(obj any) bool {
    var values reflect.Value
    if reflect.TypeOf(obj).Kind() == reflect.Ptr {
        values = reflect.ValueOf(obj).Elem()
    } else {
        values = reflect.ValueOf(obj)
    }

    for i := 0; i < values.NumField(); i++ {
        innerValue := values.Field(i)
        if innerValue.Kind() == reflect.Ptr && !innerValue.IsNil() {
            return true
        } else if !innerValue.IsZero() {
            return true
        }
    }

    return false
}

As you can see, isNil() works if I know the struct beforehand, so hasValues is false for the UserError struct, but if I call the same function using the generic struct that I created through reflect.New (unmarshalledValue), then hasValues always returns true.

What am I doing wrong here?