dimanche 30 avril 2023

Passing Java Function to KFunction

Is there any way way to pass a Function to method with parameters KFunction? I have library in kotlin which I want to make work in java but I'm unable to convert Function to KFunction (?). The function that I want to pass java function

// For example it will be in Event class
fun register(value: KFunction1<Value,Unit>) {
    ...
}

My tries to pass the function to kfunction

public class Test {
    public void launch() {
        Event.register(Test::test); // Error
    }
    @Subscriber
    public static Unit test(Value data) {
        System.out.println("Hello world!");
        return Unit.INSTANCE;
    }
}

PS. I need it to be KFunction due to usage of annotation





jeudi 27 avril 2023

Get fields of a class including the fields of objects with in a class using Java Reflection

Problem: I need to get all fields of a class including fields from properties whose type of another class.

Example:

class A { int test1, string test2, class B classb }

class B { string test3 }

Out-put should be test1, test2, test3

It looks like I need to use getDeclaredFields() on the class but how can I achieve above ?

Tried getDeclaredFields() but it only gives fields from one class

NOTE: the classes are actually POJO models.





Deep copy in golang

Trying to optimize the performance replacing the calls with json serde included with direct calls. But got issues with type conversion - although types are identical and conversion via json is possible, direct conversion is not. Conversion using json is not ok for performance reasons: we've got huge sctructures from https://www.tmforum.org/ API's Is there any package with deep copy (deep convert) functionality and optimal performance?

Tried jsoniter and conversion using json - performance is not ok and can be obviously optimized.

Need a DeepConvert func which can pass the following test:

func DeepCopy(from any, targetType reflect.Type) (any, error) {

}

type SubStructFrom struct { IntField int StrField string IntArrayField []int }

type DeepStructFrom struct { IntField int StrField string SubStructField SubStructFrom SubStructArray []SubStructFrom }

type SubStructTo struct { IntField int StrField string IntArrayField []int }

type DeepStructTo struct { IntField int StrField string SubStructField SubStructTo SubStructArray []SubStructTo }

func DeepCopy_test(t *testing.T) { from := DeepStructFrom{ IntField: 3, StrField: "", SubStructField: SubStructFrom{ IntField: 7, StrField: "Str7", IntArrayField: []int{7, 6, 5}, }, SubStructArray: []SubStructFrom{SubStructFrom{ IntField: 1, StrField: "Str1", IntArrayField: []int{0, 1, 2}, }, SubStructFrom{ IntField: 2, StrField: "Str2", IntArrayField: []int{1, 2, 3}, }}, } to, _ := DeepCopy(from, reflect.TypeOf(DeepStructTo{})) require.Equal(t, 3, to.(DeepStructTo).IntField) }





mercredi 26 avril 2023

Having a hard time with reflection in golang

I am trying to dynamically design a protocol test.

The function which I need to use is go-ethereum's Decode: https://github.com/ethereum/go-ethereum/blob/master/p2p/message.go#L54

Then some of my code uses it:

   msg <- receive() //sends me a message of type p2p.Msg

   var message MyTargetType
   msg.Decode(&message) // this works correctly and this is apparently the correct way to use the function, with a pointer to the variable

   anotherMessage := output.Msg // this is an interface{}, see below
   msg.Decode(&anotherMessage) // this fails

I don't understand why the Decode method handles the two differently. A little test program:

package main

import (
    "fmt"
    "reflect"
)

type mystruct struct {
    hello string
}

func main() {
    var first mystruct
    second := mystruct{}

    fmt.Println(reflect.TypeOf(first))
    fmt.Println(reflect.TypeOf(second))
}

This prints the types to be the same:

main.mystruct
main.mystruct

But somehow, Decode above, which uses reflection internally, handles them differently.

What's my problem? For my protocol test, I want to define the type of the output to be expected:

type Output struct {
  Msg interface{}
}

Since the messages can be of very different type, I thought the only way is to use interface{}. Therefore:

output := Output{
    Msg: MyTargetType{}.
}
//

anotherOutput := Output{
    Msg: AnotherType{}.
}
// and so on

so that I then later can check that the output received is the one expected. But that Decode method is driving me crazy.

I have tried several things with reflection, e.g.

   var decodedMsg = reflect.TypeOf(output.Msg)
   msg.Decode(&decodedMsg)

or even

   var decodedMsg = reflect.New(reflect.TypeOf(output.Msg)).Elem().Interface()
   fmt.Println(reflect.TypeOf(decodedMsg)) //this actually prints the correct type!!! 
   // But then Decode fails nonetheless with:
   // interface given to Decode must be a pointer




Only one Rigidbody can be added to a GameObject, yet Rigidbodies lack [DisallowMultipleComponentAttribute]. Why?

Obviously GameObjects should not have more than one Rigidbody. Yet, after digging through the source code, I don't see any attribute that would cause the behaviour.

namespace UnityEngine
{
...
    [RequireComponent(typeof(Transform))]
    [NativeHeader("Modules/Physics/Rigidbody.h")]
    public partial class Rigidbody : UnityEngine.Component
    {
    ...

How does UnityEngine know to not allow more than one Rigidbody on a GameObject? Is it in Rigidbody.h, or perhaps in some other editor script? I would like to determine if a component can be added to a GameObject using reflection, which is why I'm looking for a [DisallowMultipleComponent] attribute and am discombobulated by its absence.





mardi 25 avril 2023

Why below function is not being optimized by using delegate?

I have below function to send the log. And I used to have a reflection approach.(The commented code inside the function). I would like to optimize the reflection, after some investigation online, I ended with below solution and it still took me the same time. (20 secs for processing 100k log records). Can anyone help/guide me why?

public static class JsonHelper
{
    private static readonly ConcurrentDictionary<Type, Func<object, object>> _delegateCache = 
        new ConcurrentDictionary<Type, Func<object, object>>();

    private static readonly ConcurrentDictionary<Type, PropertyInfo[]> _propertyCache =
        new ConcurrentDictionary<Type, PropertyInfo[]>();

    public static string ToJson(this object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

    /// <summary>
    /// Create LogEventInfo object. 
    /// </summary>
    /// <param name="data"></param>
    /// <param name="message"></param>
    /// <param name="ex"></param>
    /// <returns></returns>
    public static LogEventInfo ToLogEventInfo(this ILogItem data, string message, Exception ex = null)
    {
        var eventInfo = new LogEventInfo();

        if (ex != null)
            eventInfo.Exception = ex;

        if (data != null)
        {
            data.EventMessage = message;
            data.LogTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Utc);
            data.LogId = Guid.NewGuid();


            //var properties = data.GetType().GetProperties();
            //foreach (var property in properties)
            //{
            //    eventInfo.Properties[property.Name] = property.GetValue(data, null);
            //}

            //Cache the delegate with expression tree.
            if (!_propertyCache.TryGetValue(data.GetType(), out var propertyInfo))
            {
                var properties = data.GetType().GetProperties();
                var delegateProperties = new Func<object, object>[properties.Length];

                for (int i = 0; i < properties.Length; i++)
                {
                    delegateProperties[i] = GenerateGetterLambda(properties[i]);

                    var propertyName = properties[i].Name;
                    var propertyValue = delegateProperties[i].Invoke(data);
                    _delegateCache.TryAdd(properties[i].PropertyType, delegateProperties[i]);

                    eventInfo.Properties[propertyName] = propertyValue;
                }
                _propertyCache.TryAdd(data.GetType(), properties);
            }
            else
            {
                var properties = propertyInfo;

                var length = properties.Length;
                for (var i= 0; i < length; i++)
                {
                    if (_delegateCache.TryGetValue(properties[i].PropertyType, out var propertyDelegate))
                    {
                        eventInfo.Properties[properties[i].Name] = propertyDelegate.Invoke(data);
                    }
                }
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(message))
                eventInfo.Message = message;
        }

        return eventInfo;
    }

    /// <summary>
    /// Combined with expression tree to futher improve the performance.
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    private static Func<object, object> GenerateGetterLambda(PropertyInfo property)
    {
        var expParameter = Expression.Parameter(typeof(object), "instance");
        var expInstance = Expression.TypeAs(expParameter, property.DeclaringType);
        var expProperty = Expression.Property(expInstance, property);
        var expPropertyObj = Expression.Convert(expProperty, typeof(object));
        return Expression.Lambda<Func<object, object>>(expPropertyObj, expParameter).Compile();
    }
}




Separate implicit vs. explicit definition of equals/hashCode for Java Record, via reflection?

Is it possible to determine (via Reflection) for a Java Record class, if it has an implicit or explicit definition of equals() and/or hashCode(Object)?

For some reflection-based meta-validation of all classes (and thus, also records) across the codebase, we'd like to separate these cases.

As far as I can see, analyzing a record-class through reflection treats both the implicit and explicit as a "declared" method of the concrete type, so I don't see a way to make that distinction.

Sample code (showing there's a declared method in both cases):

public class Test {

  public static void main(String[] args) throws Exception {
    analyze(R1.class);
    analyze(R2.class);
  }

  private static void analyze(Class<?> clazz) throws Exception {
    List<Method> hcMethods = Arrays.stream(clazz.getDeclaredMethods())
        .filter(m -> m.getName().equals("hashCode") && m.getParameterTypes().length == 0)
        .toList();
    System.out.format("Class %s has %s declared hashCode() method(s)\n", clazz.getSimpleName(), hcMethods.size());
  }

  public record R1() { }

  public record R2() {
    @Override
    public boolean equals(Object obj) {
      return obj == this;
    }
  }
}

Is there a way to still make this separation, in some other way?





dimanche 23 avril 2023

How can I determine if C# lambda captures outer variables?

I'm implementing framework where developers can add their own code as lambdas. I'd like to prevent them from sharing common state in those lambdas, but I don't know how to check if lambda uses variables from its scope. Is there a way to do it?

I've looked for a way to call lambda in the context of another object (like in JS), but apparently .NET doesn't work like that ;-) So I'm looking for different approach.





Reflexion not working has expected - What is wrong?

I try to get statitics on method execution using a annotation on my code.

Here is the code for the annotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.function.Supplier;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;

public class StatsMethodCall {
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Stats {
    }
    
    public static class StatsRegistry {
        private MetricRegistry metricRegistry;

        public StatsRegistry(final MetricRegistry metricRegistry) {
            this.metricRegistry = metricRegistry;
        }

        public void addInvocation(final String methodName, final long duration) {
            Timer timer = metricRegistry.timer(methodName);
            timer.update(duration, java.util.concurrent.TimeUnit.MILLISECONDS);
        }

        public Timer getTimer(final String methodName) {
            return metricRegistry.timer(methodName);
        }
    }
    /**
     * Get the statistics based on the method name in the Stack.
     * This is a work around because it doesn't require the @Stats Annotation. 
     * Check Method statsMethod2.
     * @param <T>
     * @param method
     * @param statsRegistry
     * @return
     */
    public static <T> T statsMethod(final Supplier<T> method, final StatsRegistry statsRegistry) {
        final String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        T result;
        final Timer.Context timerContext = statsRegistry.getTimer(methodName).time();
        try {
            result = method.get();
        } finally {
            timerContext.stop();
        }
        return result;
    }
    /**
     * Get the statistics based on the method with @Stats Annotation.
     * Doesn't work has expected
     * @param <T>
     * @param method
     * @param statsRegistry
     * @return
     */
    public static <T> T statsMethod2(final Supplier<T> method, final StatsRegistry statsRegistry) {
        String methodName = null;
        for (final StackTraceElement element : Thread.currentThread().getStackTrace()) {
            try {
                final Method m = Class.forName(element.getClassName()).getDeclaredMethod(element.getMethodName());
                if (m.getAnnotation(Stats.class) != null) {
                    methodName = m.getName();
                    break;
                }
            } catch (final ClassNotFoundException | NoSuchMethodException e) {
                // do nothing
            }
        }
        if (methodName == null) {
            throw new IllegalStateException("Cannot find method annotated with @" + Stats.class.getSimpleName());
        }

        T result;
        final Timer.Context timerContext = statsRegistry.getTimer(methodName).time();
        try {
            result = method.get();
        } finally {
            timerContext.stop();
        }
        return result;
    }
}

And I try to test the code with JUnit


import java.util.function.Supplier;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;

class StatsMethodCallTest {

    static MetricRegistry metricRegistry = new MetricRegistry();
    static StatsRegistry registry = new StatsRegistry(metricRegistry);
    static MyClass myClass = new MyClass();
    

    public static class MyClass {
        @Stats
        public String myMethod(final String arg1, final int arg2, final double arg3) {
            try {
                Thread.sleep(10);
            } catch (final InterruptedException ie) {
                ie.printStackTrace();
            }
            final String result = "Hello " + arg1 + " " + arg2 + " " + arg3;
            System.out.println(result);
            return result;
        }
    }

    @BeforeAll
    static void setUpBeforeClass() throws Exception {
        metricRegistry = new MetricRegistry();
        registry = new StatsRegistry(metricRegistry);
    }

    @AfterAll
    static void tearDownAfterClass() throws Exception {
    }

    @BeforeEach
    void setUp() throws Exception {
        
    }

    @AfterEach
    void tearDown() throws Exception {
    }

    /**
     * Workaround - I'm not fan of this
     */
    @Test
    final void test() {
        
        for(int i =0; i <100; i++) {
            //Here is the correct call
            StatsMethodCall.statsMethod(() -> myClass.myMethod("foo", 42, 3.14), registry);
        }
        
        //I tried without Lambda Expression just in case it was related to this
        for(int i = 0; i < 100; i++) {
            StatsMethodCall.statsMethod(new Supplier<Object>() {
        @Override
        public Object get() {
            return myClass.myMethod("foo", 42, 3.14);
        }
            }, registry);
        }       
        
        //This works but is weird code
        Timer timer = registry.getTimer("test");
        System.out.println("Invocation count: " + timer.getCount());
        System.out.println("Min duration: " + timer.getSnapshot().getMin());
        System.out.println("Max duration: " + timer.getSnapshot().getMax());
        System.out.println("Avg duration: " + timer.getSnapshot().getMean());
        
        //This doesn't work
        Timer timer2 = registry.getTimer(MyClass.class.getDeclaredMethods()[0].getName());
        System.out.println("Invocation count: " + timer2.getCount());
        System.out.println("Min duration: " + timer2.getSnapshot().getMin());
        System.out.println("Max duration: " + timer2.getSnapshot().getMax());
        System.out.println("Avg duration: " + timer2.getSnapshot().getMean());
    }
    
    /**
     * This is how I would like it works
     * Note: I'm calling statsMethod2 here !
     */
    @Test
    final void test2() {
        
        for(int i =0; i <100; i++) {
            //Here is the correct call
            StatsMethodCall.statsMethod2(() -> myClass.myMethod("foo", 42, 3.14), registry);
        }
                
        Timer timer = registry.getTimer(MyClass.class.getDeclaredMethods()[0].getName());
        System.out.println("Invocation count: " + timer.getCount());
        System.out.println("Min duration: " + timer.getSnapshot().getMin());
        System.out.println("Max duration: " + timer.getSnapshot().getMax());
        System.out.println("Avg duration: " + timer.getSnapshot().getMean());
    }

}

Help and explanation highly appreciated.

Thanks Kind regards

I expect that the Java Reflexion ill find the method with an anntation @Stats.

But there is no such method with @Stats annotation in the stack Very strange





samedi 22 avril 2023

Set up properties dynamically in DTO object from the output of RowCallBackHandler in spring-boot application

Below is my DTO object and I am constructing SQL query based on the user selection.So,it can be having any set of properties from the DTO class.

Eg: Sample SQL queries: (Any combination)
select res.NAME from RESPONSE res ;
select res.NAME , res.CITY from RESPONSE res ; 
select res.NAME , res.PRICE from RESPONSE res ;
....
select res.* from RESPONSE res ; 


@Entity
@Table(name="RESPONSE")    
public class Response{
    
    @Cloumn("NAME")
    private String name;
    @Cloumn("CITY")
    private String city;
    @Cloumn("AMOUNT")
    private BigDecimal amount;
    ...
    @Cloumn("PRICE")
    private BigDecimal price;
    }
    
    List<String> userSelectionList=getUserSelectionList();
    String sql=generateSqlBasedOnUserSelection();
    List<Response> responseList=new ArrayList();
    jdbcTemplate.query(sql,new RowCallBackHandler(){
    
    public void processRows(ResultSet resultSet) throws SqlException{
     Response response=new Response();
    //How will set the properties in Response object from ResultSet.

     responseList.add(response);

    }




vendredi 21 avril 2023

Declare type dynamically in GoLang

I have a field struct type:

{
Name: "fieldA",
Type: "string",
}

and an array of this filed type:

[{
Name: "fieldA"
Type: "string"
},
{
Name: "filedB",
Type: "int",
}
...

This array may change or grow later.

Now I want to define a new struct type based on this array in runtime, like this:

type myStruct struct {
fieldA string,
fieldB int,
...
}

I think using reflection, I can get a myStruct instance by calling reflect.StructOf() but can I get the type? Is this possible?

Thanks





jeudi 20 avril 2023

C# safe interface method invoking

I've got class that provides some data. I receive access to it through Remoting and call it's methods. But sometimes connection breaks. I want to have one method that is wrapping calls to this DataProvider, which first checks connection, reconnects if necessary and than invokes that method. In .Net there is MothodInfo, MethodBase and etc. But I didn't succeded trying to write such mechanism.

        public interface IDataProvider
        {
            void SomeMethod();
            void someParametrizedMethod(int p1);
            void someParametrizedMethod2(int p1, string p2);
            object someParametrizedMethodWithReturnValue(int p1, string p2);
            List<string> someParametrizedMethodWithReturnValue2(int p1, string p2);
        }

        public class DataProviderConnector
        {
            public T SafeCallToServer<T>(???)
            {
                // Check if connection is alive and reconnect if necessary
                Reconnect();
                // Invoke that ??? method and return T result
            }

            private void Reconnect()
            {
                // Do reconnect
            }

            IDataProvider serverValue;
            public IDataProvider Server
            {
                get
                {
                    if (serverValue == null)
                        serverValue = (IDataProvider)Activator.GetObject(typeof(IUltimaServer), GetServiceUrl(typeof(IUltimaServer)));

                    return serverValue;
                }
            }
        }

        public class UserClass
        {
            public UserClass()
            {
                var connector = new DataProviderConnector();

                // I want to be able to make calls like this
                connector.SafeCallToServer(IDataProvider.someParametrizedMethod2(1, "123"));
                // Or like this
                connector.SafeCallToServer(IDataProvider.someParametrizedMethod2, new object[] { 1, "123" });
            }
        }

Does anyone have some suggestions how do it?





mercredi 19 avril 2023

Mapping Dictionary

Decided to use Mapster instead of writing my own conversion/mapping methods. Haven't found anything that would suffice my use case on their github wiki.

I have an instance of Dictionary<string, string> where keys are property names of target type and values are string representations of that property value on the target type.

Here's an example of target type:

public sealed class TriggerSettings
{
    public bool ShouldRun { get; set; }
    public SimpleTriggerRecurringType RecurringType { get; set; } // enum
    public SimpleTriggerDayOfWeek DayOfWeek { get; set; } // enum
    public int Hour { get; set; }
    public int Minute { get; set; }
    public int Second { get; set; }
}

Keys in the dictionary may be incorrect and the key set may not contain all the target property names. I want to take all the valid property names and map string representations on according properties of the target type, but with a condition that I already have the target type instance and do not want to change properties, that are not present in the dictionary.

Is there a simple way to create such configuration with TypeAdapterConfig once or it can be only resolved at runtime for specific dictionary instance?

Previously I used my own simple method, that used reflection and looked like this

public static void ConvertAndMapKeyValuePairsOnObject<T>(T obj, IDictionary<string, string> propertyNameValuePairs)
{
    var properties = typeof(T).GetProperties(
        BindingFlags.Public |
        BindingFlags.NonPublic |
        BindingFlags.Instance);

    foreach (var property in properties)
    {
        if (!propertyNameValuePairs.ContainsKey(property.Name))
        {
            continue;
        }

        var converter = TypeDescriptor.GetConverter(property.PropertyType);
        var result = converter.ConvertFrom(propertyNameValuePairs[property.Name]);
        if (result is null)
        {
            continue;
        }

        property.SetValue(obj, result);
    }
}




mardi 18 avril 2023

Performance impact of reflection when creating the Json object

I have below code to prepare the logEventInfo object to log the data. I am using the Nlog. I found it is convenient to use reflection to add the name and value dynamically. But I know there is a big performance impact.

public static LogEventInfo ToLogEventInfo(this ILogItem data, string message, Exception ex = null)
        {
            var eventInfo = new LogEventInfo();

            if (ex != null)
                eventInfo.Exception = ex;

            if (data != null)
            {
                data.EventMessage = message;
                data.LogTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Utc);
                data.LogId = Guid.NewGuid();

                var properties = data.GetType().GetProperties();
                foreach (PropertyInfo property in properties) //Possibly a performance impact.
                {
                    eventInfo.Properties[property.Name] = property.GetValue(data, null);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(message))
                    eventInfo.Message = message;
            }

            return eventInfo;
        }

This ToLogEvenInfo function will be called in a loop. The data will be looped may be millions. Is there a better way to implement the below function? Thanks a lot.





lundi 17 avril 2023

Accessing nested items through reflection

Given the following F# code

namespace NS

type A() =
    let agent = MailboxProcessor.Start(fun mbx ->
        let mutable field: int = 0
        
        let f1() = 5

        let rec loop () = async {
            try 
                match! mbx.Receive() with
                | _ ->
                    let f2() = 6
                    ()
            with | _ -> ()
            
            return! loop() }

        loop ())

module B = 
    let a = A()

how to reach 'field', 'f1' and 'f2' through reflection starting from 'a' (or typeof<A>)?





Reflection POCO class and auto CreateInstance via .net6

The front-end only needs to pass in the entity name to achieve database queries,there is my code:

var entityType = Assembly.Load("system.domain").GetTypes().Where(a => a.Name == "AccountType").FirstOrDefault();
var repositoryType = typeof(infra.IRepository<>).MakeGenericType(entityType);
//????: CS0118 error,how to fix the error.
var r = ServiceLocator.Current.GetInstance<infrastructure.IRepository<????>>();

thanks!





samedi 15 avril 2023

Passing Information from one controller to another

I am currently new to JavaFx and encountering these errors when trying to pass text from a text field from one scene to another. The entire process is handled by controllers as below:

below is my login controller accessed from the main page:

public class LoginController {

    @FXML
    public TextField username;

    public void login(ActionEvent event) throws IOException {
        String usernameInfo = username.getText();

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("home.fxml"));
        Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        Scene scene = new Scene(fxmlLoader.load());

        HomeController home = fxmlLoader.getController();
        home.displayName(usernameInfo);

        stage.setScene(scene);
        stage.setTitle("Home Page");
        stage.show();
    }

}

below is my home page controller that is supposed to be accessed after a login:

public class HomeController {
    @FXML
    public Label usernameLabel;

    public void displayName(String username) {
        usernameLabel.setText("Hi there," + username);
    }
}

these are the two errors i am encountering when running the application the moment i click a login button that invokes the login method above


Caused by: java.lang.reflect.InvocationTargetException

Caused by: java.lang.IllegalStateException: Location is not set.

Can you help explain what am I doing wrong?

I looked up similar issues where the location to the home.fxml needs to be an absolute path i.e

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("home.fxml"));

to

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("com/example/secondlessons/home.fxml"));

and i still get the same error





vendredi 14 avril 2023

How do I extract methods from a class object to use in a lambda expression?

I have a section of code that looks like this, repeated several times:

net.messageBuilder(AddLingeringEffectS2CPacket.class, id(), NetworkDirection.PLAY_TO_CLIENT)
    .decoder((buf) -> new AddLingeringEffectS2CPacket(buf))
    .encoder((msg, buf) -> msg.toBytes(buf))
    .consumer((msg, ctx) -> msg.handle(ctx))
    .add();

This is a lot of boilerplate. I figured I could create a method that just takes in the class reference, the id, and the NetworkDirection, and from there I could extract the constructor and the methods from the class object to reduce said boilerplate. This looks like:

private static <MSG extends IMessage> void buildMessage(Class<MSG> clazz, int id, NetworkDirection direction)
{
    INSTANCE.messageBuilder(clazz, id, direction)
            .decoder(buf ->
            {
                return clazz.getConstructor(FriendlyByteBuf.class).newInstance(buf);
            })
            .encoder((msg, buf) ->
            {
                clazz.getMethod("toBytes", FriendlyByteBuf.class).invoke(msg, buf);
            })
            .consumer((msg, ctx) ->
            {
                clazz.getMethod("handle", Supplier.class).invoke(msg, ctx);
            });
}

(Omitted a bunch of try/catches for clarity, a lack of exception handling definitely isn't the issue.)

Unfortunately, the library I'm working with (Minecraft Forge's Simpleimpl networking system) throws some very undescriptive errors at runtime whenever this code's hit, so I'm lost as to what exactly's wrong.

Invalid message AddLingeringEffectS2CPacket




jeudi 13 avril 2023

Filter some columns from IQueryable in c#

I need to remove some columns from an IQueryable that include another object using reflection (so i don't want to use anonymous type for create the new IQueryable without a columns).

I've tried this but this isn't the right solution:

    string[] columnsToRemove = { "Insurance" };
    var myQuery = _dataService.GetQuery<Insurance>().Include(i => i.Partner);

    var attributes = myQuery.GetType().GetProperties();

    foreach (var attribute in attributes)
    {
        foreach (var column in columnsToRemove)
        {
            if (attribute.Name != column)
            {
                // Remove the column from query
                var newQuery = myQuery.Where(t => t.GetType().GetProperty(column).Name != column);
                return newQuery;
            }
        }
    }




Create an Anonymous Function with no Parameter in Scala

We know that in Scala reflection, we can invoke a method using

clazz.getDeclaredMethod("method").invoke(instance, parameters)

where the function signature of invoke is Object invoke(Object obj, Object... args).

If we want to make an anonymous function for the above with one parameter, we can write as

val method: Function1[Object, Object] = clazz.getDeclaredMethod("method").invoke(instance, _)

My question is, how to make an anonymous function with NO parameter?

Simply writing clazz.getDeclaredMethod("method").invoke(instance) will call the method without any argument, instead of making it as an anonymous function.





mardi 11 avril 2023

Is there a generic way to recursively check a deserialized object for null fields?

I receive a number of different messages that I deserialize into very dissimilar objects

Most of these objects have non-nullable fields, but across all the message types (From GraphQL, Azure service- and storage-bus, to CosmosSB and probably more that I am forgetting) some of them are happy to deserialize into objects with null fields anyway.

As such, I could very much use a component that will let me do

T objectFromMessage = GetObject(message);
FieldAsserter.AssertAllFieldsSet<T>(objectFromMessage); //Throws if any non-nullable fields are null

Do you know if any such field validation method already exists, either by default or somewhere in Nuget? Alternatively, if I have to write it myself, can you give me any clues re. where to start looking?

What did you try and what were you expecting?

Nothing really, at this point - A cursory search of NuGet and a few thoughts about reflection is as far as I got before thinking "Maybe SO has an answer."

There are a couple of similar questions on SO already, but they appear to work for single objects - the answers are of type "write an extension method to your class that does it" but I would like a generic method that'll work for anything - I have too many message types.





How to solve java.lang.reflect.InaccessibleObjectException in a maven spring project?

I wanted to update a spring application built with maven from java 8 to java 17 but because of the Java Platform Module System, I got the following exception: Unable to make field private byte[] javax.crypto.spec.SecretKeySpec.key accessible: module java.base does not "opens javax.crypto.spec" to unnamed module @234523ab.

As I read in previous posts, I tried to open the package javax.crypto.spec to all unnamed modules by adding the following plugin to my pom.xml file:

<plugin> 
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <argLine>@{argLine}
      --add-opens java.base/javax.crypto.spec=ALL-UNNAMED
    </argLine>
  </configuration>
</plugin>

However, I still get the same exception. Does anyone know how to fix this problem within a maven spring application? Also, I read that --add-opens should only be used as a work-around, so does anyone knows a better solution?





dimanche 9 avril 2023

Need help grouping annotated classes in Android Kotlin project

I'm currently working on a project where I need to group classes annotated with the @MainType and @SubType annotations. The @MainType annotation is applied to the superclass, while the @SubType annotation is applied to the subclasses.

I'm trying to achieve this using Kotlin reflection, but I haven't been successful so far.

Here's an example of what I'm trying to achieve:

@MainType
open class Animal {
    // ...
}

@SubType("dog")
class Dog : Animal() {
    // ...
}

@SubType("cat")
class Cat : Animal() {
    // ...
}

I want to group the Dog and Cat classes under the Animal class, like so:

val typeTable = hashMapOf(
    "Animal" to hashMapOf(
        "dog" to Dog::class,
        "cat" to Cat::class
    )
)

I want to achieve this using reflection.

I'm not very familiar with using reflection in Kotlin, but I've tried playing around with it to achieve my goal. Still no success





Kotlin Reflection check if class property is ArrayList of specific type

I'm a bit new with Kotlin and Java and have following question: how to check if reflected property type is ArrayList of specific type, for example is ArrayList<Pair<String, ByteArray>>?

Code behind:

        class DataUploadFormData {
            var files: ArrayList<Pair<String, ByteArray>> = arrayListOf()
            var collection: String? = null
        }

        // DataUploadFormData type is passed here as T
        suspend inline fun <reified T : Any> mapFormData(data: MultiPartData): T? {
            val formData: FormData = getFormData(data)
            val model: T? = getValue()
            var fields = T::class.memberProperties
            fields.forEach { field ->
                if (field is KMutableProperty<*>) {
                    setFieldValue(field, formData, model)
                }
            }

            return model
        }


        @OptIn(ExperimentalStdlibApi::class)
        fun <T> setFieldValue(field: KMutableProperty<*>, formData: FormData, model: T?) {
            var value: Any? = null

            if (field.returnType.javaType == String::class.createType().javaType ||
                field.returnType.javaType == Int::class.createType().javaType ||
                field.returnType.javaType == Double::class.createType().javaType
            ) {
                value = formData.fields.firstOrNull(predicate = { it.first == field.name })?.second
            }
            else if (
            // check if field.returnType is of ArrayList<Pair<String, ByteArray>> type?
            ) {
                value = formData.files
            }

            field.setter.call(model, value)
        }

Checking simple data types works well but have no idea how to check if reflected property is of complex types. I tried to instantiate property and use is or instanceof but I couldn't instantiate property with code like that field.returnType.javaType::class.createInstance(). Check field.returnType.classifier is ArrayList<*> returns false.





samedi 8 avril 2023

Is there any way to return comma separated string containing the values of the properties of a C# object.?

Looking for Solution to return property names on header and then values

public override string ToString()
    {
        StringBuilder builder = new StringBuilder();
        var props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); //        string typeName = this.GetType().Name;


        var itemStr = string.Join(", ",
       props.Select(p => p.GetValue(this,null)? .ToString())
          .ToArray());
        return itemStr.ToString();

    }
}

I try to use string. Join but its returning only values like john, smith.But I need in following format. "firstname","lastname" and then in next line its values "John","smith" "Mary","land"





How to use an extension delegate to references other extension methods [closed]

I'm trying to make a delegate assignment to methods that are contained inside a library of extension indicator methods. The signature of the library methods is represented by the "Indic" extension below. The code below is a rough idea of what I'm trying to achieve went evaluating a library method with the named indicator, passed in via the indicator parameter. The example code is not passing the input list to library extension property... and that's the problem I'm having.

I looked at stackoverflow question: Extension method calling other extension wethod (not really applicable)

I'm also confused at when I should use generic delegate extensions.

using Infrastructure;
using Skender.Stock.Indicators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;

    public static class IndicatorExt
    {
        public static object? Indic<T>(this T quote,
            string indicator, int? LookBack = null)
            where T : List<RawTick>
        {
            // Get a MethodInfo that represents indicator.
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static;
            MethodInfo? minfo = typeof(Indicator).GetMethod(indicator, flags);

            // Get the Type and MethodInfo. These string are for testing 
            Type? MyType = Type.GetType("System.Reflection.FieldInfo");
            MethodInfo? Mymethodinfo = MyType?.GetMethod("GetValue");

            // I'm not sure on how to pass the input data quote (per above)
            return Mymethodinfo?.Invoke(null, new Object?[]
                { guote, indicator, LookBack }); //******* quote is unaccessible
        }
    }

I also need to know how to pass the list into the delegate as input.

    public void main()
    {
        var quotes = new List<RawTick>(Enumerable.Range(1, 25)
            .Select((x, i) => new RawTick() { Close = x, Open = i }));

        Func<List<RawTick>, string, int?, object?> results = IndicatorExt.Indic;
        var ind = (List<AdxResult>)quotes.results(CalcAdx", 8);
        MessageBox.Show($"{ind.Count}");
    }





vendredi 7 avril 2023

Converting a String into a Constructor to make a new Object

@NotNull
public static String toString(@NotNull Object object, @NotNull Object[] variables, Class<?>... parameters) throws NoSuchMethodException {
    StringBuilder sb = new StringBuilder();
    sb.append(object.getClass().getConstructor(parameters)).append('\n');
    sb.append(object.getClass()).append(":");
    for (Object variable : variables){
        sb.append(" | ").append(variable.toString());
    }
    return sb.toString();
}

A brief explanation of the code, the toString() method uses an object, the variables of the constructor that the user wants to save, and the parameters of a constructor. This method would form the parameters in a way like this:

public User(java.lang.String,int)
class User: | username | 369172

I want to use this String format to convert the above into a new instance of the Object that was taken in using the method below:

public static Object toObject(@NotNull String formattedObject, @NotNull Object object, Class<?>... parameters){
    // The code I need to figure out.
}

I want to figure out: how to get all the variables cast into a form where I could use them to make a new instance of the object if I didn't know how many variables/parameters there are, how to use the method in the event the constructor of the Object is private, and if one of the parameters is an Object that prints out the default Object toString() method. How could I do this?





How to trigger a callback when field is changed using reflection in c#

For example I want to log the Name value every time it changes.

using System;

class Data {
    public string Name;
    
    public Data(string name) {
        Name = name;
    }
}

public class Test
{
    public static void Main()
    {
        Data data = new("foo");
        
        object name = typeof(Data).GetField("Name").GetValue(data);
        
        Console.WriteLine(name);
    }
}




jeudi 6 avril 2023

Method to Serialize and Deserialize an Object using java.lang.reflect (Java)

I'm trying to make a method in Java that allows me to convert an Object's constructor and the values used in the constructor into a String and convert the String into a method that deserializes the String and converts the String to the selected Object using the newInstance() method in the java.lang.reflect.Constructor class. I want to try an serialize an Object that doesn't implement the Serializable interface.

The way I figured I would do this is using the java.lang.reflect package and making a method that would act as an outside toString() method that takes in an Object and the parameters of the Object in the form of a Class<?>, but I don't know how to recieve the variables used to make the Object. For example, take this User object:

class User {
    private final String username;
    private int userID;
    public User(String username, int userID) {
        if (!validateUserID(userID)) {
            throw new RuntimeException("ID cannot have more or less than 6 digits!" + this.userID);
        }
        this.username = username;
        this.userID = userID;
    }
    private boolean validateUserID(int userID){
        return String.valueOf(userID).length() == 6;
    }
}

If I were to serialize this User object initialized as User user = new User("username", 985313);, I want to get the name of the class, the constructor of the class, the parameters of the class in the form of Class<?>..., and the variables used to initialize this Object. How would I go about doing this?





Dynamic subscription to event at runtime

I have implemented a very simple example on how I would want to subscribe dynamically to external events and perform some specific logic when the event is raised:

public static class ConsoleHost
{
    // Hooks onto an external event to automatically output a simple message
    public static void RegisterHook<TEventArgs>(object obj, string eventName, string message)
        where TEventArgs : EventArgs
    {
        // Create Dynamic Method
        var dynMethod = CreateHandler<TEventArgs>(() =>
        {
            Write(message);
        });
        
        // Retreive Method
        var methodInfo = dynMethod.GetMethodInfo();

        // Retreive EventInfo
        var eventInfo = obj.GetType().GetEvent(eventName);

        // Build dynamic delegate
        var dynDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, methodInfo); // <-- This fails cause of different signatures

        // Finally add EventHandler
        eventInfo.AddEventHandler(obj, dynDelegate);
    }

    // Generate Proxy EventHandler
    private static EventHandler<TEventArgs> CreateHandler<TEventArgs>(Action action)
        where TEventArgs : EventArgs
    {
        return (object? sender, TEventArgs e) => action();
    }

    // Simple Output to Console for Example Purposes
    public static void Write(string message)
    {
        Console.WriteLine(message);
    }
}

However I get an error stating, that my dynamic method has a different signature than expected. What am I missing?





How to extract type parameters using reflection

Context: I'm writing a generic auto-mapper that takes two types of structs, checks each field of said structs for a given tag, then copies the value from the source struct to the target struct assuming that they have matching tags and types. Whenever a struct field is another (nested) struct, I want the auto-mapper function to do a recursive call, auto-mapping all the way down the rabbit hole.

Problem: I'm only able to pass the concrete type of the root structs. Once I'm inside the generic function that's using reflection, trying to extract the nested struct types doesn't seem possible. While I can pass the Value.Interface() as an argument, I still need to pass the type parameters as well.

Here is some simplified code to show the problem.

type Alpha struct {
    Nested Beta `automap:"nested"`
}

type Beta struct {
    Info string `automap:"info"`
}

type Foo struct {
    Nested Bar `automap:"nested"`
}

type Bar struct {
    Info string `automap:"info"`
}

func TestAutoMap(t *testing.T) {

    b := Beta{Info: "Hello from Beta!"}
    a := Alpha{Nested: b}

    f, err := AutoMap[Alpha, Foo](a)
    if err != nil {
        fmt.Println(err)
        t.Fail()
    }
    fmt.Println("f.nested.info:", f.Nested.Info)
}

func AutoMap[S, T any](source S) (target T, err error) {

    targetStruct := reflect.ValueOf(&target).Elem()
    sourceStruct := reflect.ValueOf(&source).Elem()

    // .Type and .Kind directly did not work.
    nestedSourceType := ??? // I want this to be type Beta.
    nestedTargetType := ??? // I want this to be type Bar.

    sourceInterface := sourceStruct.Interface()

    t, err := AutoMap[nestedSourceType, nestedTargetType](sourceInterface)
    if err != nil {
        return target, err
    }
    target = t

    return target, nil
}




mercredi 5 avril 2023

The interface{} in golang confused me

everyone. If i have the following code. Why it will raise a error:

The code:

var i interface{}
v, ok :=i.(interface{})
fmt.Println(v, ok)

The error: <nil> false

Whether the dynamic type of a declarated interface{} var is nil alaways? but when it will be interface{}? What will be false any var's assertion to interface{} forever?





mardi 4 avril 2023

Kotlin enum via reflection

I wonder is there any better way to parse enum when you don't have Generic and have only KProperty1<T, *>?

I have found / come up with solution like this:

enum Car {
    BMW, AUDI
}

val property = properties[fieldName] as? KProperty1<T, *>
val instanceKClass = property.returnType.jvmErasure

if (instanceKClass.java.isEnum) {
   parseEnum(property.javaField!!.type as Class<Enum<*>>, "BMW")
}


fun parseEnum(enumClass: Class<Enum<*>>, value: Any?): Enum<*>? {
    val enumClz = enumClass.enumConstants
    return try {
       enumClz.first { it.name == value }
    } catch (ignored: Exception) {
       throw IlligalArgumentException("there is no such enum")
    }
}

I'm trying to extract enum value from string in Kotlin via reflection and I want to find best possible way of doing this

P.S. I'm looking for advice how to do it more efficient and nice, because I'm not really satisfied with this way.





lundi 3 avril 2023

C# Build anonymous type from array string

I'm looking for a way to build an anonymous type from an object where it's property names match those in a given string array. Something like:

//Current Way:
    var anonObject = primaryObject.Select(m=> new {m.property1, m.property2, m.property3, m.property4, ...etc});
//Ideal Way:
    var propertyArray= new string["property1","property3"];
    var anonObject = primaryObject.Select(m=> new { /* Something here where we step through primaryObject.GetProperties() and only choose the ones where the name is contained in the above array */ });

Any ideas on how to achieve this?





dimanche 2 avril 2023

Reflection getMethod(...) throws NoSuchMethodException with a different method name

Using myClass.getMethod("func_181057_v") throws exception in the console - "NoSuchMethodException: myClass.v()".
Why is the method name different in thrown exception compared to what I've actually typed in and how can I retrieve that method?

I have tried both .getMethod(..) and .getDelcaredMethod(..) as well as printed .getDeclaredMethods() list and .func_181057_v() was on the list.

My code:

try {
   Class<?> fmlCommonHandlerClass = Class.forName("net.minecraftforge.fml.common.FMLCommonHandler");
   Class<?> minecraftServerClass = Class.forName("net.minecraft.server.MinecraftServer");
   Class<?> playerListClass = Class.forName("net.minecraft.server.management.PlayerList");

   Method getMinecraftServerInstanceMethod = fmlCommonHandlerClass.getDeclaredMethod("getMinecraftServerInstance");
   Method getPlayerListMethod = minecraftServerClass.getDeclaredMethod("getPlayerList");
   Method getPlayersMethod = playerListClass.getMethod("func_181057_v");
} catch (Exception exception) {
   throw new RuntimeException(exception);
}

Exact method name is public java.util.List net.minecraft.server.management.PlayerList.func_181057_v()
If you want to execute it you need to compile and install it as a plugin to Mohist server, I'm using version 1.12.2, build 320.

Full exception:

[18:25:56 ERROR]: Error occurred while enabling ReflectionExample v1.0-SNAPSHOT (Is it up to date?)
 java.lang.RuntimeException: java.lang.NoSuchMethodException: net.minecraft.server.management.PlayerList.v()
        at com.example.plugin.reflectionExample.ReflectionExample.onEnable(ReflectionExample.java:20) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:177) ~[JavaPlugin.class:?]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:318) [JavaPluginLoader.class:?]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:399) [SimplePluginManager.class:?]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugin(CraftServer.java:477) [CraftServer.class:?]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugins(CraftServer.java:418) [CraftServer.class:?]
        at net.minecraft.server.MinecraftServer.func_71247_a(MinecraftServer.java:383) [MinecraftServer.class:?]
        at net.minecraft.server.dedicated.DedicatedServer.func_71197_b(DedicatedServer.java:315) [nz.class:?]
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:590) [MinecraftServer.class:?]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_361]
Caused by: java.lang.NoSuchMethodException: net.minecraft.server.management.PlayerList.v()
        at java.lang.Class.getMethod(Unknown Source) ~[?:1.8.0_361]
        at com.mohistmc.bukkit.nms.proxy.ProxyClass.getMethod(ProxyClass.java:43) ~[ProxyClass.class:?]
        at com.example.plugin.reflectionExample.ReflectionExample.onEnable(ReflectionExample.java:18) ~[?:?]
        ... 9 more