jeudi 30 juin 2022

Unable to assign interface object pointer in golang

I am making a function that will unpack arbitrary variable types from a variadic parameter into variables like so:

package main

import (
    "fmt"
)

func unpackVariadic(variadic []interface{}, into ...*interface{}) {
    for i, v := range into {
        *v = variadic[i]
    }
}

func Update(variadic ...interface{}) {
    var a, b interface{}
    unpackVariadic(variadic, &a, &b)

    a = "Hey"
    b = "Hello"
}

func main() {
    a, b := "Hola", "Hola"
    Update(&a, &b)
    fmt.Println(a)
    fmt.Println(b)
}

However, it is printing "Hola", "Hola" instead of "Hey", "Hello" how I would like.

My understanding is that a and b in Update() and main() have different reference values, meaning reassigning from within Update() will just locally assign a and b from the addresses of original a and b to the values of the new strings.

To solve this, I tried reassigning a and b by their object pointers:

func Update(variadic ...interface{}) {
    var a, b *interface{}
    unpackVariadic(variadic, a, b)

    *a = "Hey"
    *b = "Hello"
}

But, when I do, I get invalid operation: cannot indirect a (variable of type interface{}).

So, why am I unable to assign by object pointers in Update() while I am allowed to in unpackVariadic? How could I go about this differently?





How is the IsDefined method internally implemented in C# .Net?

As can be seen from the Microsoft reference source code:

    public virtual bool IsDefined(Type attributeType, bool inherit)
    {
        throw new NotImplementedException();
    }

All overloads for IsDefined boil down to this one.

So how is this method implemented internally or is it implemented by the compiler?





Instantiate different versions of same class with changed constructor and "abstract" modifier

I am writing a Java program which uses external libraries. I want to write my code so it is compatible with two different versions of one specific library.

The problem is, they changed a class (called Configuration in my example) to abstract, added an abstract method and changed the constructor from a no-argument to parameterized constructor. I am not able to influence the external library and I have to work with what I got.

Old class example

public class Configuration {

    public Configuration() {
        //Some code...
    }

    public static void main(String[] args) {
        Configuration conf = new Configuration();
        //Some code...
    }

}

New class example

public abstract class Configuration {

    public Configuration(boolean isCool, Map<String, String> entries, Object otherThing) {
        //Some code...
    }

    public abstract int doSomething();
    
    public static void main(String[] args) {
        Configuration conf = new MyConfiguration(false, null, new Object());
        //Some code...
    }

}

My implementation

public class MyConfiguration extends Configuration {
    
    public MyConfiguration(boolean isCool, Map<String, String> entries, Object otherThing) {
        super(isCool, entries, otherThing);
    }
    
    public MyConfiguration() {
        //needs super constructor call!?
    }

    public int doSomething() {
        //Some code...
        return -1;
    }

    public static void main(String[] args) {
        int version = 0;
        Configuration conf = version > 2 ? new MyConfiguration(false, null, new Object()) : new MyConfiguration();  
        //Some code...
    }

}

IDE error

The no-argument constructor of my custom class MyConfiguration needs to call the constructor of the superclass in order to be compiled. However, the old class does not have a parameterized constructor, so I will run into an error if I do that.

  • Are there any tricks how I don't have to call the super constructor?
  • Maybe there is a way using reflection to do what I want?




Call JsonProperty setter method from a dependent class

I have a class as follows:

public class MyClass {
   @JsonProperty("my_id")
   private String id;

   @JsonProperty("my_list")
    private List<SecondClass> myList;

   public getId() {
      return this.id;
   }

   public setId(String id) {
      this.id = id;
   }

   public getMyList() {
      return this.myList;
   }

   public setMyList(List<SecondClass> myList) {
      this.myList = myList;
   }
}

My class has a dependency on another class called SecondClass [through the List entity]

public class SecondClass {
   @JsonProperty("my_name")
   private String name;

   public getName() {
      return this.name;
   }

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

I know how to access the getters and setters of "MyClass" using Reflection based on the JsonProperty name, as shown below:

public void myMethod(MyClass myClass, String jsonProperty, String newId) throws IllegalAccessException {
    for (Field field : MyClass.class.getDeclaredFields()) {
        JsonProperty jsonPropAnnotation = field.getAnnotation(JsonProperty.class);
        if (jsonPropAnnotation != null)
            if (jsonPropAnnotation.value().equals(jsonProperty)) {
                field.setAccessible(true);
                field.set(myClass, newId);
            }
    }
}

But, my question is, is there a way to fetch the getter and setter from SecondClass via MyClass based on the JsonProperty name using Reflection?

As an example I would like to call getList() based on JsonProperty value "my_list" and then setName() based on the JsonProperty value "my_name".

Is this a possibility using reflection?





mardi 28 juin 2022

Kotlin set lazy field through Java reflection

I'm trying to play around with Java reflection in Kotlin, and I have the following field in my Kotlin class:

val tree: Tree by lazy { 
    getTree(hashGroup, service) 
}

I'd like to set this field through Java reflection, and so far I got to this point:

val tField = transaction::class.java.getDeclaredField("tree\$delegate")
tField.isAccessible = true
tField.set(transaction, newTree)

Obviously this is not going to work, because the tree field has a delegate (tree$delegate) and it wants me to set it to a Lazy class type and not Tree type.

I know the easiest would be to actually add a setter for this field in the main class but I can't really modify the API and I need this for a resilience test case. Is this even possible to do?





Alternate way to call method

I have a generic method that accepts two parameters string and object. It is supposed to invoke a method based on string name. The other parameter is received as object which is basically object parameter of the target method.

I am currently maintaining a dictionary that keeps dictionary against passed string and the actual method. Like

public static Dictionary<string, string> ActionMappings = new Dictionary<string, string>
   {
       { "Get Patients", "Patient.GetPatients" },
       /// other mapping...
    };

I am currently invoking the method based on ActionMappings dictionary. I am using reflection like

string className = methodDetailsValues.Split('.')[0];
string methodName = methodDetailsValues.Split('.')[1];
currMethodClass = Type.GetType("NameSpace" + className);


ConstructorInfo stringConstructor = allConstructorsOfClass.First();
object newStringConstructor =  stringConstructor.Invoke(null);
MethodInfo voidMethodInfo = currMethodClass.GetMethod(methodName);
object jsonString =       voidMethodInfo.Invoke(newStringConstructor, new object[] { });

Can I maintain a list of initialized methods? It is working but it seems to be slow in performance.





Java - Not able to get value of Custom Annotation using Reflection

I'm trying to generate a report and the fields should be in the specified sequence. As this is microservices architecture, I've a db service where interface based projection is used. On top of it, I'm trying to use a custom annotation to maintain the order.

Custom Annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Sequence {
        int value();
}

Interface based Projection DTO :

public interface ReportDTO {

@Sequence(value = 1)
String getId();

@Sequence(value = 2)
String getName();

@Sequence(value = 3)
String getMobileNumber();

}

In another micoservice, I'm deploying this db service and utilising as below:

private static List<String> getFieldNamesForClass(Class<?> clazz) throws Exception {
    List<String> fieldNames = new ArrayList<String>();
    Method[] methods = clazz.getMethods();

    Arrays.sort(methods, (o1, o2) -> {
        boolean isPresent = o1.isAnnotationPresent(Sequence.class);
        
        Sequence or1 = o1.getAnnotation(Sequence.class);
        Sequence or2 = o2.getAnnotation(Sequence.class);
        // nulls last
        if (or1 != null && or2 != null) {
            return or1.value() - or2.value();
        } else
        if (or1 != null && or2 == null) {
            return -1;
        } else
        if (or1 == null && or2 != null) {
            return 1;
        }
        return o1.getName().compareTo(o2.getName());
    });
    for (Method method : methods) {
        if (method.getName().substring(0, 3).equals("get") && !method.getName().equals("getDecoratedClass")
                && !method.getName().equals("getTarget") && !method.getName().equals("getTargetClass"))
            fieldNames.add(lowerFirst(method.getName().substring(3)));
    }
   
    return fieldNames;
}

But this code is unable to figure out the annotation. Variable "isPresent" returns false and or1 and or2 are null. Please help me figure out the issue with this code.





samedi 25 juin 2022

How to get the fields and under fields in an Object via reflection?

can we retrieve the value of the fields of a class as well as the value of the fields of the classes it contains ?

Example :

public class Person {
    private String lastName;
    private String firstName;
    private Address address;
}

public class Address {
    protected String street;
    private String city;
}

I want to retrieve these values :

lastName firstName street city





vendredi 24 juin 2022

Alternative to Assembly.ReflectionOnlyLoad() and ReflectionOnlyLoadFrom()?

I'm migrating a .Net 4.x application to .Net 6, but the above methods are now deprecated and throw an exception if called. What are the alternatives?

This is the code, which gets passed a list of assembly filenames, and loads any assemblies found to have a certain assembly-level attribute in AssemblyInfo.cs:

AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve +=
    (s, e) => Assembly.ReflectionOnlyLoad(e.Name);

foreach (var assemblyFile in assemblyFilenames)
{
    var reflectionOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile);
    if (FoundOurCustomAttr(reflectionOnlyAssembly))
    {
        var assembly = Assembly.LoadFrom(assemblyFile);
        ProcessAssembly(assembly);
    }
}




jeudi 23 juin 2022

How to create a compatible delegate from its type?

I'm trying to create a Standard library with common types for WPF/UWP etc.
Since many types are not in Standard, sometimes you have to use reflection.
In this connection, the task of creating a DispatchedHandler from an Action arose.
In UWP, this is easy: new DispatchedHandler(action);.
But in Standard I only have Type from DispatchedHandler.

    private object GetDispatchedHandler(Action action)
    {
        // Some code 

        dispatchedHandlerType = windowsAssembly.GetType("Windows.UI.Core.DispatchedHandler");

        // Next, you need to transform the `action` and return it from the method.
        return Activator.CreateInstance(dispatchedHandlerType, action);
    }

This code throws an exception: "Constructor on type 'Windows.UI.Core.DispatchedHandler' not found".

But can get a constructor from a type: dispatchedHandlerType.GetConstructors()[0].
The constructor has the following signature: {Void .ctor(System.Object, IntPtr)}.
The first parameter, I think, should be passed action.
What should be passed as the second parameter?
dispatchedHandlerConsructor.Invoke(new object[] { action, ??? });





Java8 - Dynamic Casting for Reflection value assignment

I want to get the header value from the reply of http call, store it in cache and use this value in next requests by passing it to header of the http requests in order to achieve sticky session. My project is in Java 8.

I have feign http client builder like this which decode using JacksonDecoder.

   public <T> T buildClient(Class<T> type, String url) {
            return Feign.builder()
                    .contract(new JAXRSContract())
                    .encoder(new JacksonEncoder(mapper))
                    .decoder(new CustomDecoder(mapper))
                    .logger(new Slf4jLogger(Constants.APIC_LOGGER_NAME))
                    .logLevel(Level.FULL)
                    .options(new Options(connectTimeout, readTimeout))
                    .retryer(Retryer.NEVER_RETRY)
                    .requestInterceptor(auth2FeignRequestInterceptor)
                    .requestInterceptor(requestInterceptor())
                    .invocationHandlerFactory(factory)
                    .target(type, url);
        }

The default decoder from jackson decode only body not header so I am implementing my own CustomDecoder.

What I want to achieve is get the value of the resonse.headers and map it to body

public final class CustomDecoder extends JacksonDecoder implements Decoder {
    @Override
      public Object decode(Response response, Type type) throws IOException {
          //Here the default decoder only decoding body.
          Reader reader = response.body().asReader();
   Object responseBodyObject = mapper.readValue(reader, mapper.constructType(type));

Now I want to do the dynamic casting to the Object above so that after I get my class in runtime I am able to assign the header value inside the body through Java Reflection. but Dynamic casting is not working as below.

How to make the below casting work in runtime so that I assign the value to the object using reflection?

 Class<?> myclass= Class.forName(type.getTypeName());
 myclass.cast(responseBodyObject);




Java generics, constraining the type to the 'self' type

This is a rather specialized question and I doubt there is a solution.

I've got a type hierarchy like A {}, B extends A{}, C extends A {}. A defines an abstract method <T extends A> T scale(double v).

The problem is that T is not anchored and you can assign the result to any type.

The solved this problem in enum (and that is why I think there is no solution) by declaring the 'self' type as a generic parameter:

 class A<T extends A<T>> { T scale(double v) { ... ;} }
 class B extends A<B> {}
 class C extends A<C> {}

Another solution would be to write the scale method in each subclass:

 class A<T extends A<T>> { A scale(double v){...} }
 class B extends A<B> { B scale(double v) { super.scale(v);}}
 class C extends A<C> { C scale( double v) { super.scale(v);} }

However, this is all ugly and lots of work.

I do not see why the compiler could not solve this problem. (I am probably missing something.) What I would like is something like this:

 class A { this scale(double v); }

Now this clearly does not work but I wonder if people found interesting generic hacks to constrain a generic return type or a generic parameter to the 'current' type the compiler observes.





mercredi 22 juin 2022

accessible: module jdk.proxy9 does not "opens jdk.proxy9" to unnamed module

Unable to make field private static final java.lang.reflect.Method jdk.proxy9.$Proxy196.m0 accessible: module jdk.proxy9 does not "opens jdk.proxy9" to unnamed module @18ad9d68

I tried to upgrade my project from JDK11 to JDK17, but it had this problem, I tried to add:

--add-exports
java.base/sun.util.calendar=ALL-UNNAMED
--add-opens
java.base/sun.util.calendar=ALL-UNNAMED
--add-exports
java.base/java.util=ALL-UNNAMED
--add-opens
java.base/java.util=ALL-UNNAMED
--add-opens
java.base/java.lang=ALL-UNNAMED

But none of them worked, prompting the message“ module jdk.proxy9 does not "opens jdk.proxy9" to unnamed module”,I referred to the question I can't find a solution





Why is Spring's BeanWrapper#getPropertyValue so slow?

This is my test method.I'm trying to invoke this method 100000 times, and it cost 12000ms.

private static void test() {
    MyBean bean = new MyBean();
    Field[] fields = MyBean.class.getDeclaredFields();
    BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
    for (Field f : fields) {
        f.setAccessible(true);
        String fieldName = f.getName();
        Object fieldValue = beanWrapper.getPropertyValue(fieldName);
    }
}

And when I change the code.

private static void test() {
    MyBean bean = new MyBean();
    Field[] fields = MyBean.class.getDeclaredFields();
    BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
    for (Field f : fields) {
        f.setAccessible(true);
        String fieldName = f.getName();
        Object fieldValue = f.get(bean);
        // Object fieldValue = beanWrapper.getPropertyValue(fieldName);
    }
}

And it only costs about 400ms. Why is Spring's BeanWrapper#getPropertyValue so slow?





I'm trying to parse a struct field pointers with reflection in Golang

So i want to print the names in a struct(it can be nested), so i'm trying to use a recursive method to do the same but i'm failing to do so.Ive pasted the code below and i get the following error "panic: reflect: call of reflect.Value.NumField on zero Value". I'm able to do it when it's a flat hierarchy but failing when its nested.Any help is appreciated.Also i used this post "https://ift.tt/KEX2OoN" for reference. Also, the struct is built from protobuf hence the Ptr.

package main

import (
    "fmt"
    reflect "reflect"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}
func getFields(protoStructure interface{}) {
    val := reflect.ValueOf(protoStructure).Elem()
    // if val.Kind() == reflect.Ptr {
    // val = val.Elem()
    // }
    valNumFields := val.NumField()
    for i := 0; i < valNumFields; i++ {
        field := val.Field(i)
        fieldKind := field.Kind()
        varDescription := val.Type().Field(i).Tag.Get("description")
        // fieldKindStr := field.Kind().String()
        fieldName := val.Type().Field(i).Name
        // fieldTypeStr := field.Type().String()
        fmt.Println(fieldName, varDescription)
        if fieldKind == reflect.Ptr {
            rvAsserted := field
            getFields(rvAsserted.Interface())
            // fmt.Println(rvAsserted.Type().String())
        }
    }
    return
}
func main() {
    getFields(&DeviceEnv{})
}




mardi 21 juin 2022

C# How to create an instance of private nested class with parameters using Expression [closed]

Given the class below:

public class MyClass {
    ...
    private class NestedClass(MyClass param1, double param2, double param3, bool param4) {
        public int Property1 { get; }
        public int Property2 { get; }
    }
}

I can't access NestedClass since it is private. Still I'd like to use it. Which is the best way to instantiate the NestedClass and have access to its property? Would it be possible to achieve the result using compiled expressions maybe?

Thanks in advance for your help. Cheers. M.





Go: Is there a way to set values of a struct inside interface? [duplicate]

I'm new to Go and have this problem to which I can't find a solution (I don't even know if it is a problem or if it is the expected behavior).

I have a Struct like the following:

type Info struct {
  Id      string
  Request interface{}
}

Request can be of different types, ex.

type ReqType1 struct {
  Quantity int
  Code     float32
}

or

type ReqType2 struct {
  Name string
  Code float32
}

My question is: if I have var i of type Info, and i.Request type is ReqType2, is it possible to set the value of Name without needing another variable request (like the following)?

I know I can just do:

request := i.Request.(ReqType2)
request.Name = "Maddie"
i.Request = request

But I have a lot more attributes, and was hoping there was another way to do so. I tried using reflect pkg but couldn't get it right. I tried:

reflect.ValueOf(i.Request).Elem().FieldByName("Name").SetString("Maddie")




Dynamically create healthchecks based on all services that have a certain interface

I have a long set of services that check data, and all under the interface "IDataCheck".

In a commandline app I do:

IEnumerable<IDataCheck>? services = _serviceProvider.GetServices<IDataCheck>();
foreach (IDataCheck? s in services)
{
    DataCheckResult result = await s.RunCheckAsync();
    // all kinds of stuff with the result such as proposing to autofix
}

I now want to also present the results of these checks in asp.net core healtchecks using also the healthcheck ui, ref:

I do not want to create manually a healthcheck per data check because otherwise the usefulness of having an interface is gone

I also do not want to create one healthcheck only otherwise it will produce a long list of results all in one text only column in the ui since it does not support any formatting.

What I want is something like (but will not work):

    public static ServiceProvider AddDataHealthChecks(this ServiceProvider serviceProvider, IServiceCollection services)
{
    using IServiceScope scope = serviceProvider.CreateScope();
    IEnumerable<IDataCheck>? dataServices = serviceProvider.GetServices<IDataCheck>();
    foreach (IDataCheck? s in dataServices)
    {
        services
            .AddHealthChecks()
            .AddTypeActivatedCheck<DataQualityHealthCheck>(nameof(s),
                failureStatus: HealthStatus.Degraded,
                tags: new[] { "data" },
                args: new object[] { s });
    }
    return serviceProvider;
}

(so that based on the name it can lookup the healthcheck class and then call the RunCheckAsync on this specific one) (so that in the UI under the foldout "data" there will these seperate rows of results by the name s.name).

But this will not work since on the moment of calling this, the services are not there yet and service provider is not there yet. And i think... doing this via reflection on all IData classes in all assemblies found will result in the same failure.

So probably this will have to go after building the service collection and then via reflection and then dynamically adding it i think ?





ReflectionTestUtils set field method

Is there a way to use ReflectionTestUtils to set the return value of a method inside a field that represents a class to a mocked value instead of mocking the entire field? I was trying .setField(), but that only seems to work for the entire field. If there isn't, what would be a good substitute? Example of what I mean below:

public class Example() {
    private ClassField field;
    
    public methodThatUsesField() {

        methodReturnType type = field.method(); // I was trying to call .setField() to change the field's method to a mocked value, but can't figure out how to do it
        ...
    }
}

The class that is called in the field is very complicated, but there is a very simple public method that acts as the root of the class, and I want to set that to a specific value. The class itself does not have a constructor, so I need a way to get around that.

This is a spring boot project written in Java, and I need to use ReflectionTestUtils to be able to pass an argument into Mockito mock





lundi 20 juin 2022

LINQ - Dynamically Invoke ToDictionary

Is there a way in .Net to dynamically invoke ToDictionary(<lambda key>, <lambda val>) to reduce boilerplate of returning a Dictionary when running LINQ expressions.

C# Example:

Dictionary<string, object> d_filt;

Dictionary<string, object> d_in = new Dictionary<string, object>();
d_in.Add("k1", 4);
d_in.Add("k2", 3);
d_in.Add("k3", 2);
d_in.Add("k4", 1);

// Current Expression:
d_filt = d_in.Where(p => p.value > 2)
             .ToDictionary(p => p.Key, p => p.Value);

// Preferred Expression:
d_filt = linq2Dict(d_in.Where(p => p.value > 2));

Where linq2Dict(<LinqObj>) is a helper that will dynamically invoke the ToDictionary(..) method.

I have tried Reflection library but it appears that ToDictionary is not available through the standard Reflection library I'm familiar with.

Note: VB is even more verbose:

Dim d_filt = d_in.Where(Function(p) p.value > 2).ToDictionary(Function(p) p.Key, Function(p) p.Value)




dimanche 19 juin 2022

How does MongoRepository finds the correct collection when findById(String id) is called?

I'm trying to understand a little more about how does Spring finds the correct Collection when calling the findById(String id) method. Normally the classes that will be persisted are annotated with @Document(collection = "CollectionName") and when a basic operation like:

T save(T entity);
Optional<T> findByExample(T entity);
T update(T entity);

Seem kinda understandable that we can access the annotation data since we have the whole entity available, but when a method like:

T findById(String id)

We don't have access to the entity information, the closer we get is the Generic type T. But only with the type T we are not able to initialize a new object and get the annotations information. There is any documentation available that explains this?





java reflection on different argument number

Is it possible to pass different number of arguments to a dynamic reflection method??

I have N classes, for instance

class A { method_A(T arg1, S arg2){}}
class B { method_B(T arg1){}}
class C //... and so on

I try to build a function able to invoke any method in any class

 main(){
   Object[] args = {"arg1", "arg2"};
   foo(new A(), "method_A", args);
 }
 foo(Object obj, String objectiveMethod, Object[] params){
   Method[] allMethods = obj.getClass().getDeclaredMethods();
   for(Method method: allMethods){
     //find the objective method, irrelevant to the question
     if(objectiveMethod.equals(method.getName())){
       method.invoke(obj, params); // Here throws IllegalArgumentException: wrong number of arguments
     }
   }
 }

I can easily retrieve the amount of arguments Method.getParameterCount(), but i can't figure out how to dynamically pass N number of arguments retrieved from Object[] args;.

I thought that MethodAccessor.invoke(Object obj, Object[] args) could handle this (because of Object[] args) but it doesn't work and throws

IllegalArgumentException: wrong number of arguments

Could you help me figure out any way to achieve that? Or it's impossible?

--edit--

 f(){
   A aObj = new A(); C cObj = new C();
   Object[] args = {"arg1", "arg2"};
   Object[] argsC = {"arg1", 2, new B()};
   aObj.method_A(args[0], args[1]); // works fine
   ...
   /* It doesn't matter which type of object they are, they still have known of it's type without casting*/
   method.invoke(aObj, args[0], args[1]); // works fine
   method.invoke(aObj, args); // doesn't work, wrong number of args.


   methodC.invoke(cObj, args...?);// 3 args dynamically
 }




samedi 18 juin 2022

Why cannot modify a String field with Reflection?

JDK version: 1.8.0_291

Target class:

package reflectionStackoverflow.test;

public class ClassA {
    private final static StringBuilder nameStringBuilder = new StringBuilder("1");
    private final static String nameString = "1";
 
    public static void printNameStringBuild() {
        System.out.println("nameStringBuilder: " + nameStringBuilder);
    }
    public static void printNameString() {
        System.out.println("nameString: " + nameString);
    }
}

Test Code:

package reflectionStackoverflow.test;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectionTest {
    @Test
    public void test() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class c = ClassA.class;

        Field nameStringBuilder = c.getDeclaredField("nameStringBuilder");
        nameStringBuilder.setAccessible(true);
        Field nameStringBuilderModifiers = nameStringBuilder.getClass().getDeclaredField("modifiers");
        nameStringBuilderModifiers.setAccessible(true);
        nameStringBuilderModifiers.setInt(nameStringBuilder, nameStringBuilder.getModifiers() & ~Modifier.FINAL);
        nameStringBuilder.set(c, new StringBuilder("2"));
        nameStringBuilderModifiers.setInt(nameStringBuilder, nameStringBuilder.getModifiers() & ~Modifier.FINAL);

        Field nameString = c.getDeclaredField("nameString");
        nameString.setAccessible(true);
        Field nameStringModifiers = nameString.getClass().getDeclaredField("modifiers");
        nameStringModifiers.setAccessible(true);
        nameStringModifiers.setInt(nameString, nameString.getModifiers() & ~Modifier.FINAL);
        nameString.set(c, "2");
        nameStringModifiers.setInt(nameString, nameString.getModifiers() & ~Modifier.FINAL);

        ClassA.printNameStringBuild();
        ClassA.printNameString();
    }
}

Test result:

nameStringBuilder: 2
nameString: 1

Conclusion:

StringBuilder field can be modified with reflection, but String field can not be modified.

Question:

Why String can not be modified with reflection?

Is there any way to modify a private final static String value like above StringBuilder case?





jeudi 16 juin 2022

C# Assembly loaded in one class, throws an exception in another

I have a very weird situation here:

internal class Loader {
    internal void Load() {
        UseAssembly();
    }
    
    private void UseAssembly() {
        var marshaller = new Marshaller();
        Assembly assembly = marshaller.LoadAssembly();
    }
}

[Serializable]
public class Marshaller {
    internal Assembly LoadAssembly() {
        return Assembly.ReflectionOnlyLoadFrom("C:\\Users\\OLNO\\Downloads\\SkinProject1.dll");
    }
}

Now here is the interesting part:

enter image description here

It is interesting, because the file exists in that location, and because the exception itself is thrown at this line:

Assembly assembly = marshaller.LoadAssembly();

but not this one:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom("C:\\Users\\OLNO\\Downloads\\SkinProject1.dll"

and when instead of code above I have this one, it works just fine:

internal class Loader {
    internal void Load() {
        UseAssembly();
    }
    
    private void UseAssembly() {
        Assembly assembly = Assembly.ReflectionOnlyLoadFrom("C:\\Users\\OLNO\\Downloads\\SkinProject1.dll");
    }
}

I'm working in Visual Studio 2019, and I've tried cleaning the build and rebuilding the solution. This issue looks pretty much like magic to me... How do I fix this?

Thanks in advance.





Reading properies of an typecript class at runtime. Something like the reflection in C# or in JAVA

I've got a .ts file which contains many classes like below (Angular Project). The Classes auto generated from backend classes.

export class User {
  name: string;
  lastName: number;
  userCode: string;

}

Now, I want to read this class and its properties by its name. Then I will create the Angular input elements with this data.

For Instance (pseudo code):

let className = 'User';
  let listOfProperties = reflectObject(className)




mercredi 15 juin 2022

Why is it impossible to construct private objects through reflection in Java [duplicate]

I clearly set the constructor's setAccessible to true, but why is it still an error! can you tell me how to fix it

public class Person {
    // fields...

    private Person(String name, int age, String address, int num) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.num = num;
        System.out.println("private full-constructor be created");
    }

}

// error happend ?! why?

public static void operatePrivateConstructorFullParameter(Class<? extends Person> clzz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Constructor<? extends Person> constructor = clzz.getConstructor(String.class, int.class, String.class, int.class);
    constructor.setAccessible(true);

    Person person = constructor.newInstance("Miao", 18, "MOON", 88);
}


public static void main(String[] args) throws Exception {
    Class<? extends Person> clzz = Person.class;
    operatePrivateConstructorFullParameter(clzz);
}

enter image description here





Dart/Reflectable: How to get all subclasses from an abstract base class

I want to use the Dart/reflectable framework to find all subclasses of a specific base class and I struggle with that use case.

I have

  1. An abstract base class with a few getters:
abstract class MyBaseClass {
    String get name;
    List<MyValueType> get values;
}
  1. Several classes that implement MyBaseClass:
class A implements MyBaseClass {
   @override
   String name = 'AClass';
   
   @override
   List<MyValueType> = [MyValueType.X, MyValueType.Y]; 
}

class B implements MyBaseClass {
   @override
   String name = 'BClass';
   
   @override
   List<MyValueType> = []; 
}

My goal is to fetch all classes that implement MyBaseClass and read their properties.

So, I created:

class Reflector extends Reflectable {
  const Reflector()
      : super(invokingCapability); 
}

const reflector = const Reflector();
  1. How do I fetch a list of classes? I only found the InstanceMirror.reflect() which only delivers one result, not many.
  2. It is not clear, how the annotation must be set. When trying to fetch all MyBaseClass implementations, do I need to annotate only my abstract MyBaseClass or do I need to annotate classes A and B or do I need to annotate all three classes?
  3. Which capabilities do I need? In my test case I got this exception: NoSuchCapabilityError: no capability to invoke the getter "name" but was not able to solve this.

Thanks in advance, any help is appreciated!





Reflection added Delegate not firing

This is the code.

For example purposes, NewButton will have the name "Add", the SubMenuButtonNamesList is a list of strings containing the names of the buttons that I will be creating, afterwards I wanted to add the handler to these buttons based on the methods found in the mainwindow, matched by their names.

I think I did it properly since the button does have this handler added, but when I click the button nothing happens, it should show me a messagebox saying "yes".

public void Add_Method(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("Yes");
}
public MainWindow()
{
    InitializeComponent();

    //Create all sub-menu buttons
    foreach (var element in SubMenuButtonNamesList)
    {
        Button NewButton = new Button()
        {
            Background = new SolidColorBrush(new Color { A = 100, R = 231, G = 233, B = 245 }),
            FontFamily = new FontFamily("Century Gothic"),
            Content = element,
            FontSize = 14,
            Height = 30,
            Width = Double.NaN,
            VerticalAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Center
        };

        NewButton.Name = element.Trim();
        
        try
        {
            MethodInfo method = typeof(MainWindow).GetMethod(NewButton.Name + "_Method");
            Delegate myDelegate = Delegate.CreateDelegate(typeof(MouseButtonEventHandler), this, method);
            NewButton.MouseLeftButtonDown += (MouseButtonEventHandler)myDelegate;
        }
        catch (Exception e)
        {

        }

        SubMenuButtonsList.Add(NewButton);
    }

}




mardi 14 juin 2022

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

private const string ReferencedAssemblyName = "System.Private.CoreLib";

private delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath);
private delegate void SetDllImportResolverDelegate(Assembly assembly, DllImportResolver resolver);

private static readonly SetDllImportResolverDelegate _setDllImportResolverCallback;

static Program()
{
    Assembly coreLibAssembly = AppDomain.CurrentDomain
        .GetAssemblies()
        .FirstOrDefault((assembly) => assembly.GetName().Name == ReferencedAssemblyName);

    if (coreLibAssembly != null)
    {
        MethodInfo[] methods = coreLibAssembly
            .GetTypes()
            .FirstOrDefault((type) => type.Name == "NativeLibrary")
            .GetMethods(BindingFlags.Public | BindingFlags.Static);

        foreach (MethodInfo method in methods)
        {
            if (method.Name == "SetDllImportResolver")
                _setDllImportResolverCallback = (SetDllImportResolverDelegate)method.CreateDelegate(typeof(SetDllImportResolverDelegate));
        }
    }
}

static void Main()
{
    _setDllImportResolverCallback(typeof(NativeLibrary).Assembly, (libraryName, assembly, searchPath) =>
    {
        return NativeLibrary.Load("Kernel32");
    });
}

Im getting this exception when im trying to create delegate for "SetDllImportResolver" method. My delegate has same structure like in System.Private.CoreLib. How can i make it works?





How can I create a class derived from a reflected interface

I would like to call a method in a reflected class that takes an interface also defined in the reflected library

My library is a .NET461 library

public interface InterfaceA{
  ...
}
...
public class ClassA {
  public void MethodA( InterfaceA interface )
  {
    ...
  }  
}

My executable is a .NET48 executable

(removed validation and some code for brevity)

// get the library
var asm = Assembly.LoadFrom( "...myAssembly.dll" );

// instantiate ClassA
var instance = asm.CreateInstance( "ClassA" )

// look for that class type so we can get the method "MethodA"
var class = asm.GetExportedTypes().FirstOrDefault( t => t.Name == "ClassA" ); 

// look for the Method
var method = class.GetMethod( "MethodA");

// look for the interface
var interface = asm.GetExportedTypes().FirstOrDefault( t => t.Name == "Interface" ); 

// how can I call the method here
method.Invoke( instance, new []{ ....} );

I know everything about the interface, I can create an exact class that has the same methods and properties ...

But how can I create the same class in my code, so I can pass it as an argument to the reflected class?





Interactions between code in two unnamed modules

Premise: I have had 2 classes loaded by different class loaders - one from the app classloader and the other, a custom class loader. The class loaded by the custom class loader is trying to reflectively access a private field in the class loaded via the appclass loader. In this case, I get a runtime error along the lines of "Failed to access class A from class B; A is in unnamed module of loader 'app' and B is in unnamed module of loader 'Custom'. The error goes away after adding an '--add-opens java.base/java.lang=ALL-UNNAMED'

Questions : I understand that there can be up to one unnamed module per classloader in the VM.

  1. What part of the JLS or JDK implementation specific to hotspot VM talks about interactions between two unnamed modules across loaders ? I can see a lot of unnamed to named module interactions etc in the document, but not between two unnamed.

  2. I understand why add-opens is solving the issue in general( the code is being invoked reflectively and end calls into JDK happen via java.lang.reflect APIs?). However, unclear again as to how the add-opens works across loaders - does --add-opens=ALL-UNNAMED expected to open the packages in the specified module to all unnamed modules across loaders in the VM or only to that loader?

Using Java 17 + hotspot VM.





lundi 13 juin 2022

How to get all properties of fields in my tables from entry of dbcontext ef in c#?

this is my code:

foreach (PropertyInfo prop in typeof(myDbContext).GetProperties())
{
     if (!prop.PropertyType.Name.StartsWith("DbSet"))
     {
          continue;
     }
     var myCls = prop.PropertyType.GenericTypeArguments[0];
     var entry = _axsc05Context.Model.FindEntityType(myCls);
     var primaryKeies = entry?.FindPrimaryKey();
     var foregnKeys = entry?.GetForeignKeys();
     var myClsProperties = myCls.GetProperties();
     foreach (var p in myClsProperties)
     {
         string propertyComment=?//entity.Property(e => e.TypeMilitaryOrgan).HasComment("[myComment]");
         string propertyColumnName=?//.HasColumnName("myColumnName")
         string propertyColumnType=?//.HasColumnType("money")
         bool isGenerateNever=?//.ValueGeneratedNever()
     }
}

how can i find the values that i set in dbcontext:

string propertyComment=?//entity.Property(e => e.TypeMilitaryOrgan).HasComment("[myComment]");
string propertyColumnName=?//.HasColumnName("myColumnName")
string propertyColumnType=?//.HasColumnType("money")
bool isGenerateNever=?//.ValueGeneratedNever()

i want to get all properties of fields in my tables





What are 'real' and 'synthetic' Method parameters in Java?

Looking into j.l.r.Executable class I've found a method called hasRealParameterData() and from its name and code context I assume that it tells whether a particular method has 'real' or 'synthetic' params.

If I take e.g. method Object.wait(long, int) and call hasRealParameterData() it turns out that it returns false which is confusing to me, as the method is declared in Object class along with its params.

From this I've got a couple of questions:

  1. What are 'real' and 'synthetic' Method parameters and why Java believes that params of Object.wait(long, int) are not 'real'?
  2. How can I define a method with 'real' params?




Get reflect.Type statically without creating an object

I have this Go code:

type Op interface{}
type Op1 struct{}
type Op2 struct{}

I'm trying to map Types to int. Something like this (pseudo-code):

mapping := map[reflect.Type]int
mapping[Op1] = 20
mapping[Op2] = 30

I know this is possible by creating an instance of Op1/Op2 and call reflect.TypeOf:

op1 := Op1{}
op2 := Op1{}

mapping := map[reflect.Type]int
mapping[reflect.TypeOf(op1)] = 20
mapping[reflect.TypeOf(op2) = 30

but my question is if it's possible to do that "statically" without creating an object. Something like .class in Java.





Using reflection, how can I find the Method that takes arguments defined in the reflected library itself?

I have a library written in .NET461 and I would like to call a method in that library using reflection

The class itself looks something like ...

public class ClassA {
}
...
public class ClassB {
  public MethodA( ClassA val )
  {
    ..
  }  

  public MethodA( List<ClassA> list )
  {
    ..
  }  
}

My calling exe is a .NET48 executable...

(removed validation and some code for brevity)

// get the library
var asm = Assembly.LoadFrom( "...myAssembly.dll" );

// instantiate ClassB
var instance = asm.CreateInstance( "ClassB" )

// look for that class type so we can get the method "MethodA"
var type = asm.GetExportedTypes().FirstOrDefault( t => t.Name == "ClassB" ); 

// look for all the methods called "MethodA"
// this call works and I can see I have 2 methods with that name
var methods = type.GetMethods().Where(m => m.Name == "MethodA").ToList();

// look for the method just by that name.
// Here I get an error as there are 2 methods with the same name.
var method = type.GetMethod( "MethodA");

It is possible to get the method if I pass the parameters but the 'type' in the list is supposed to be a list of List<ClassA>

How can I find the method with a parameter of "List<ClassA>" when ClassA itself is defined in the library and not in my executable.

...
var methodA = type.GetMethod("MethodA", new []
          {
            typeof(List<ClassA>>)                  // <<<< ClassA is not defined here. 
                                                   //      It is defined in the library
          } );




dimanche 12 juin 2022

Modifying JSON element of type "dynamic"

I am trying to deserialize some JSON data, make a modification to a small part of the data, and re-serialize back into JSON format.

The JSON data looks something like this:

{
    "name": "...",
    "type": "...",
    "values": [0, 1, "apple", ...],
    ...
}

values is a mixed-type array with an unknown number of elements, and as such I use the dynamic type for its C# model:

public class Model
{
    [JsonPropertyName("name")]
    public String Name { get; set; }
    [JsonPropertyName("type")]
    public String Type { get; set; }
    [JsonPropertyName("values")]
    public dynamic Values { get; set; }
    ...
}

Deserializing the object is simple:

Value = model.Values[0].GetDouble();

However, I am unable to write to it because dynamic is apparently read only:

model.Values[0] = 1.0;

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Property or indexer 'System.Text.Json.JsonElement.this[int]' cannot be assigned to -- it is read only'

How can I accomplish this?





How would you make a custom attribute that injects code into a class or method in C#?

I've been learning C# and WPF lately and keep seeing people using attributes to "inject" or modify code inside of a class or method like this and I'm wondering how/if it is even possible to make something of the sort using custom attributes:

Here is an older example of how an attribute from a NuGet package (FodyWeavers) shortens code by automatically raising the PropertyChanged event when any setter belonging to a public property in the class is called:

[ImplementPropertyChanged]
public MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    public string MyProperty { get; set; }
}

Without the attribute, this would have to look like:

public MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    private string myProperty;
    public string MyProperty
    {
        get { return myProperty; }

        set
        {
            myProperty = value;
            PropertyChanged(this, new PropertyChangedEventArgs());
        }
    }
}

Everywhere I look online I keep running into the same brick wall saying "custom attributes are just metadata and do nothing by themselves without external code". My question is, where is this external code placed so that attributes can be recognized and acted upon? What would this external code look like so that such functionality is possible? Is this even possible with custom attributes and reflection alone or is there something else behind the scenes that I'm missing?

Thanks.





samedi 11 juin 2022

Iterate over dynamic object fields and get field data type

I have object in dynamic type, and index variable in Int data type. Is it possible to get type of field of dynamic object in given index? For better understanding you can imagine my question like so:

dynamic dynamicObject = ...
var type = GetType(dynamicObject.Fields[index]); // Int, String or another.

I fabricated this code for a better understanding. That's why maybe this code view is a little bit absurd :)

For instance

dynamic dynamicObject = new
{
   Name = "Bla",     
   Age = 2,
   Surname = "Bla Bla"
};
int index = 2;

And I want to get System.String

Thanks in advance :)





vendredi 10 juin 2022

I want to set a few string properties to an Object using Reflection. How do I do that in C#? [duplicate]

I am creating a website using N-Tier with an MVC front-end in Visual Studios 2019 using .NET Framework in C#. I have a few strings that I am sending over to the model from my controller (currently hard-coded for example purposes, but in reality this information would come from the domain tier using dapper to reach my database and extract the information):

[HttpGet]
public ActionResult Index()
{
    IndexViewModel model = new IndexViewModel("a", "b", "c", "d");
    return View(model);
}

When the program gets to the model I want to take these strings and box them inside of a new private object via the constructor. Then I want to create a protected internal method called ChurchContactInformation that returns that same object unboxed with the information contained inside of it to send over to the view (cshtml page) to show to the user. This is what I have tried but I keep getting a null exception error.

private object churchInformation;

    public IndexViewModel(string churchLocation, string churchPhoneNumber, string churchEmail, string onlineWorshipLink)
    {
        
        churchInformation = new object();
        churchInformation.GetType().GetProperty(churchLocation).GetValue(churchLocation);
        churchInformation.GetType().GetProperty(churchPhoneNumber).GetValue(churchPhoneNumber);
        churchInformation.GetType().GetProperty(churchEmail).GetValue(churchEmail);
    }

    protected internal object ChurchContactInformation ()
    {
        return churchInformation.GetType().Attributes;
    }
}

I am pretty new to reflection, would anyone be able to help with this?





Is there any way of modifying a function internal variable at runtime in Java? [closed]

Is there any way of modifying a function internal variable at runtime in Java?

For example:

public static String foo(String a, String b){
    boolean flag = flagService.select();
    if(flag){
        return a + b;
    }else{
        return a + ',' + b;
    }
}

 public static void main(String[] args) {
     //what I want got: modify flag at runtime and got 2 different result.
     String a = "a";
     String b = "b"
     //TODO: do something modify inner method variable flag = true
     String res1 = foo(a,b);
     //TODO: do something modify inner method variable flag = false
     String res1 = foo(a,b);
     //TODO: contrast res1 and res2
 }

Java Reflection can modify class filed, but can not modify method.

why I want to do that: Every time, Our test engineer should both verity result the of flag true and false. I try to write a freamwok can contrast both result at runtime when difference and do not modify their code.





jeudi 9 juin 2022

Get all classes that extends a class in nodeJS

so basically I have a this code where classes extends over a base class

class CommandBase {
    doCommand(){
        // Do command thing.
    }
}

class Help extends CommandBase{

}

class Kick extends CommandBase{
    
}

class Ban extends CommandBase{
    
}

class Chat extends CommandBase{
    
}

now throughout the production of the program more and more commands will be added that extends the CommandBase class, is there any way via reflection I can just get all classes the extends the CommandBase classes without to explicitly write them in an array or keeping track of them by writing manually on code? I want to have something like this in C#:

AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p))

Can nodeJS do this? is there any specific reflection library for it?





How to make a Map object from Field(reflect) with all values?

I have a field annotated with the MaskedMap annotation and it is a Map class. Then I get this field through the annotation search and I want to get all the values of this field that are in the Map. And I can't make from field to Map

private void putMapParamsMasks(Class<?> type) {
                    for (Field field : type.getDeclaredFields()) {
                        MaskedMap maskedMap = field.getAnnotation(MaskedMap.class);
                        if (maskedMap != null) {
                            for (int i = 0; i < maskedMap.keys().length; i++) {
                                try {
                                    Map<String, String> map = (Map<String, String>) field.get(new HashMap<String,String>()); //failed
                                    valueMasks.put(map.get(maskedMap.keys()[i]), maskedMap.masks()[i].newInstance());
                                } catch (InstantiationException | IllegalAccessException e) {
                                    throw new UnexpectedException(e);
                                }
                            }
                        }
                    }
                }

I tried to do it like this:

Map<String, String> map =(Map<String, String>) field.get(type);

But I caught it

java.lang.IllegalArgumentException: Can not set java.util.Map field com.ConfirmRequest.params to null value




Runtime error with a very basic reflection example in C#

I'm trying to learn a bit more about System.Reflection using the official microsoft docs. Specifically I'm trying to run the following example:

// Loads an assembly using its file name.
Assembly a = Assembly.LoadFrom("MyExe.exe");
// Gets the type names from the assembly.
Type[] types2 = a.GetTypes();
foreach (Type t in types2)
{
    Console.WriteLine(t.FullName);
}

So I made a new console app using dotnet new console -o=customconsole. I then removed ImplicitUsings from my project file (because I don't like that), and came up with the following code:

using System;
using System.Reflection;

namespace get_type_from_assembly 
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // load assembly using full file name
            Assembly a = Assembly.LoadFrom("C:\\Users\\bobmarley\\desktop\\temp\\csharp-reflection\\get-type-from-assembly\\bin\\Debug\\net6.0\\console-custom.exe");
            // get type names from assembly
            Type[] types2 = a.GetTypes();
            foreach (Type t in types2)
            {
                Console.WriteLine(t.FullName);
            }

        }
    }
}

Then I tried to run the generated executable using dotnet run --project=customconsole. I got the following runtime error:

Unhandled exception. System.BadImageFormatException: Bad IL format. The format of the file 'C:\Users\bobmarley\desktop\temp\csharp-reflection\get-type-from-assembly\bin\Debug\net6.0\console-custom.exe' is invalid.
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at get_type_from_assembly.Program.Main(String[] args) in C:\Users\bobmarley\desktop\temp\csharp-reflection\get-type-from-assembly\Program.cs:line 11
make: *** [Makefile:5: run] Error 1

I'm not sure why this occurs, because I checked and the executable does exist in the specified path. What is happening here and how can I fix it?





How to read kotlin annotation

I have annotation classes

annotation class Endpoint(val name: String)

@Target(AnnotationTarget.TYPE)
annotation class JsonObjectKey(val name: String)

These are used like so

@Endpoint("my-endpoint")
fun myEndpoint(): @JsonObjectKey("key") String {
    return "value"
}

With a method: java.lang.reflect.Method object representing myEndpoint, I am able to access the Endpoint-Annotation, but I fail to access the JsonObjectKey-Annotatation.

method.annotations only contains Endpoint

method.annotatedReturnType.annotations is empty

How to read JsonObjectKey (key in this scenario)? Intention is to generate JsonObject {"key": "value"}





mercredi 8 juin 2022

Is it possible to get the position in code of e.g. MemberInfo?

The question

Is there a way to get the position in code of where an attribute has been used, or the location where a member variable has been declared?

I am not searching for a workaround for this problem, only for a simple answer if this is technically possible or not.

Some background information

I have defined an attribute that connects a member to a VisualElement in a Unity UI Document using the parameters provided to the Attribute. Here's an example:

[Query("button-upvote")]
private Button _buttonUpvote;

Now in some situations the element does not exist, which means _buttonUpvote cannot be resolved, maybe because there is a typo, in which case I want to log a warning to the Unity console. In this warning I get a stack trace, but I don't get a stack trace that leads me to the attribute or the member in question as in the above example, it leads me to the code that logged the warning, which is totally unrelated to the actual error in this case. I would like to include the position where the Query attribute has been used, in the warning log.





Get property default value as expression using reflection

In order to build a custom transpiler, I'm trying to get the default value of all the properties inside a class as an expression, and not as a value itself.

Let me bring you some examples to clarify what I'm trying to do and what I've done/tried/investigated so far.


Source code could be the following one:

const string DATETIME_NOW = "____DATETIME_NOW____";

public class Person {
  [DefaultValue("Foo")]
  public string Name { get; set; } = "Foo";

  [DefaultValue(DateTime.Now)] // This is not doable: "An attribute argument must be a constant expression"
  public DateTime DateOfBirth { get; set; } = DateTime.Now;

  [DefaultValue(DATETIME_NOW)]
  public string DateOfBirthStringed { get; set; } = DATETIME_NOW; // which acts like DateTime.Now.ToString()
}


The ultimate goal of the transpiler, is to obtain a Javascript class that looks like this:

class Person {
  name: string = "Foo";
  dateOfBirth: Date = new Date(Date.now());
  dateOfBirthStringed : Date = Date.now();
}

My current, and working, implementation is the use of DefaultValue attribute with some constants strings used when the default value is an expression (e.g. DateOfBirthStringed). What I'm doing is using reflection on Person, getting all the PropertyInfo, looking for their DefaultValue attribute, and then checking if the given default value are some fixed constants like DATETIME_NOW.

This works, but I've a couple of problems:

  1. The type in attribute DefaultValue could be different from the type of the property.. No type check :(
  2. If I only have the DefaultValue, when I write new Person(), the default values are not actually set from the attribute.
  3. Therefore, I need to write the default value after { get; set; }, but:
    1. Or I wrote both attribute and default value, but then I should manually mantain synchronized them.
    2. I write only the default value, but then I've no way to get it with reflection.

About point 3.2, why I can't get the default value via reflection? Suppose the Person class defined above; if I use reflection, I need to instantiate it, but once instantiated, Person.DateOfBirth has an actual DateTime value, and I cannot know it was coming from DateTime.Now.

Also, if Person would be abstract.. Well, no way to instantiate it.


So, basically, the only way I could perfectly transpile the code is to read the code as a tree, something like parseTreeCode(typeof(Person)). At that point, I should navigate the tree and be able to do everything I want.

I did find Roslyn, which allows me to parse C# code, but.. It parses "stringed" code, and not code that belongs to the same project. I thought "well, get the file where Person is defined, and parse the whole file", but unfortunately, once the program is running, I cannot get the file where Person is defined.. I mean, I can do typeof(Person).Assembly, and getting the Assembly.. But it would be an assembly, so it would not be good.


At this point, I'm thinking that there is no real solution for this, but maybe I'm missing some C# packages/features that could help me





mardi 7 juin 2022

Java Spring Argument Type Mismatch at org.sql2o.reflection.MethodSetter.setProperty(MethodSetter.java:27)

I've got this error that sometimes shows up. When I reload the project disappears, only to show up again at random, and I don't know why it happens.

I invoke this method in the EmployeeRepositoryImpl class:

@Override
public Employee getById(Long idemployee) {
    logger.info("GET EMPLOYEE BY ID");
    try (Connection con = sql2o.open()) {
        return con.createQuery("SELECT e.EMPLOYEEID, e.NAME, e.SURNAME, CONCAT( e.SURNAME, CONCAT(' ',e.NAME)) AS NOMINATIVO, e.TAXCODE, e.CONTRACTTYPE, e.CONTRACTEXPIRY, e.EMPLOYEETYPE, e.FLGACTIVE," +
                        " e.SUPPLIERID, e.INSERTEDBY, e.INSERTEDON, e.MODIFIEDBY, e.MODIFIEDBY, e.MODIFIEDON, e.SUBCONTRACTORCOMPANY FROM EMPLOYEE e where e.EMPLOYEEID = :employeeid")
                 .addParameter("employeeid", employeeId)
                 .executeAndFetchFirst(Employee.class);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw e;
    }
}

by using this

Employee employee = employeeService.getById(employeeId);

The Employee class is:

public class Employee {

private Long employeeid;
private String name;
private String surname;
//other properities

public Long getEmployeeid() {
    return employeeid;
}

public void setEmployeeid(Long employeeid) {
    this.employeeid = employeeid;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
//other getters and setters

The error is this

java.lang.IllegalArgumentException: argument type mismatch
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.sql2o.reflection.MethodSetter.setProperty(MethodSetter.java:27)
at org.sql2o.DefaultResultSetHandlerFactory$6.handle(DefaultResultSetHandlerFactory.java:236)
at org.sql2o.PojoResultSetIterator.readNext(PojoResultSetIterator.java:33)
at org.sql2o.ResultSetIteratorBase.safeReadNext(ResultSetIteratorBase.java:88)
at org.sql2o.ResultSetIteratorBase.hasNext(ResultSetIteratorBase.java:52)
at org.sql2o.Query.executeAndFetchFirst(Query.java:618)
at org.sql2o.Query.executeAndFetchFirst(Query.java:607)
at it.niuma.epp.repository.EmployeeRepositoryImpl.getById(EmployeeRepositoryImpl.java:78)

Let me know if others information or bits of code are needed. Thanks!





Kotlin: IllegalArgumentException while trying to call function of other classes by reflection

I try to call methods by reflection in kotlin and it doesn't work.

My code (simplyfied, null-checks and catch-exceptions omitted):

class MyCallerClass() {

  val allCallableMethods: List<KFunction<Unit>> = ... 

  // request: we're within a web-page. The user can see the callable methods and click which one to call 
  fun handleRequest(request: HttpServletRequest) {

    val callableMethodName = request.getParameter(callableMethodNameParam)
    if (callableMethodName != null) {
      for (method in allCallableMethods) {
        if (method.name == callableMethodName) {
          // we found the method the user wants to call!

          val paramMap: MutableMap<KParameter, Any> = mutableMapOf()
            
          // this part I added after I got an IllegalArgumentException. See below
          if (method is CallableReference) {
            paramMap[method.instanceParameter!!] = method.owner
          }

          for (param in method.valueParameters) {
            val paramName = if (param.name != null) {
              param.name!!
            }

            val paramValue: String? = request.getParameter(paramName)
            if(paramValue != null) {
              paramMap[param] = paramValue
            }
          }

          method.callBy(paramMap)
        }
      }
    }
  }
}

So first I only collected all params in the paramMap, but that resulted in "java.lang.IllegalArgumentException: No argument provided for a required parameter: instance parameter of fun...".

Luckily I found questions here that helped me on:

So I added the part with if (method is CallableReference). But now I get a "java.lang.IllegalArgumentException: object is not an instance of declaring class".


I also tried to use method.call() instead of method.callBy():

...
var paramArray = arrayOf<Any>()
...
paramArray = paramArray.plus(paramValue)
...
method.call(*paramArray)

But that gave the same results. Without the instance-parameter I get a "java.lang.IllegalArgumentException: Callable expects 2 arguments, but 1 were provided.". With the instance-parameter the same "java.lang.IllegalArgumentException: object is not an instance of declaring class"


Then I tried to call a method within the same class: I created a new method in MyCallerClass:

fun myLocalMethod(strParam: String, intParam: Int): String {
  return strParam
}

and then I added this in fun handleRequest:

val myLocalMethodFunc = ::myLocalMethod
val returnStr = myLocalMethodFunc.call("test", 3)

And it worked! o_O


So can anyone explain

  • why the call to the local function works and to the remote function doesn't? They're both of the type KFunction.
  • how I can call the remote functions? How do I provide the instanceParameter in the correct way?
  • why I can't debug into method.callBy() or method.call()? That would help me a lot, but IntelliJ just jumps over it.




lundi 6 juin 2022

How to randomly change a form using relfection from a specified list of forms?

I want to write a code that pops up a random form from a specified list of forms when a button is pressed in winforms.

The forms in the specified list include Form1, Form2, and Form3. It must not be moved to a form other than the specified forms.

The code I'm using now works using switch() and if(). However, when increasing or decreasing the number of Forms, it is cumbersome to modify all kinds of places.

So I thought, how can I solve this using reflection?

I know how to change the form.

private void ChangeForm()
{
  var form = new Form1();
  form.ShowDialog();
}

The part I'm stuck on is that I'm not sure what to do when I use the new keyword to specify the form I want to change.

Any help would be appreciated.





Springboot using reflection with stream

i would filter the result of my pagination result in springboot by iterating on all fields , i have the idea to iterate on each result and call each getter method of this object to compare it to my keyword (im doing smart search) , but i dont call each method hard coded cause the structure may change in fututr and there is a lot of feilds , i would to know how to pass each getters to stream

i already found how to get method with :

for(PropertyDescription Introspector.getBeanInfo(Myclass).getPropertyDescriptors()){
                  propertyDeescriptor.getReadMethod()}

thank you a lot





Resolve enum class variable name to string [duplicate]

Consider, I have got the following enum class:

enum class TestEnum
{
   None = 0,
   Foo,
   Bar
};

I'd like to specify ostream operator ( << ) for this enum class, so I could write:

std::cout << "This is " << TestEnum::Foo;

and get following output This is Foo.

My question is:
Is there any place where enum "name specifiers" are stored? (i.e. for enum class TestEnum it is None, Foo and Bar) So I could write a function (or at best function template) that specifies ostream operator for this TestEnum like:

std::ostream& operator<< ( std::ostream& os, TestEnum aEnum ) {
   return std::string( aEnum.name() );
}

So far, I did it this way:

std::ostream& operator<< ( std::ostream& os, TestEnum aEnum ) {
   switch( aEnum )
   {
   case TestEnum::Foo:
       os << "Foo";
       break;
   case TestEnum::Bar:
       os << "Bar"
       break;
   }
   return os;
}

I have seen some solutions using boost library, but I would prefer not using it this time.





"Unable to find compatible protocol (h2)" when using BouncyCastleFipsProvider as a ssl provider for Grpc java client

on my program startup I setup my jdk provider by 'Security.addProvider(new BouncyCastleFipsProvider());' I use it in the Grpc client by '''SslContextBuilder sslContextBuilder = SslContextBuilder.forClient() .sslProvider(SslProvider.JDK) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, Collections.singletonList("h2")));''' When trying to establish the connection, After successful ssl handshake I get:

Failed ALPN negotiation: Unable to find compatible protocol using io.grpc 1.44 version + bc-fips.jar 1.0.2 version. Running by java 11.0.15 compiled by jdk1.8.0_291.jdk. It looks like BouncyCastleFipsProvider, by its SSLParamertesUtil class, somehow remove the "h2" from the suggested application protocols list. increasing grpc version to 1.46 didn't help any suggestions please? Thanks.





dimanche 5 juin 2022

Get Java runtime classes as byte array while filtering out local classes

I want to get any java runtime classes as a byte array. Currently I am looking them up using ClassLoader.getSystemClassLoader().getResourceAsStream(...) to get the class as an input stream and then convert it to a byte array. How can I ensure that the classes loaded are only runtime classes of Java itself (Object.class etc.), while classes that are application specific (stored in the JAR file / classpath) are blocked due to security reasons?





Not able to get class with ClassLoader once SpringBoot app completely initialized

I run Spring Boot project in jar and I try to get class by class name from external library with ClassLoader:

Thread.currentThread().getContextClassLoader().loadClass(className)

When I call this from @PostConstruct method it returns correct result but when I call it after app initialization I am getting java.lang.ClassNotFoundException.

I also tried to get class like this but it didn't work correctly once app started:

Class.forName(className, true, Thread.currentThread().getContextClassLoader())

Can somebody please explain what the issue is?





Is the built-in LambdaMetafactory parameter type checking correct?

For example, when I execute the following:

public static int addOne(Number base) {
  return base.intValue() + 1;
}

public static interface AddOneLambda {
  public int addOne(Integer base);
}

public static void main(String[] a) throws Throwable {
  Method lambdaMethod = AddOneLambda.class.getMethod("addOne", Integer.class);
  Class<?>[] lambdaParameters = Stream.of(lambdaMethod.getParameters()).map(p -> p.getType()).toArray(Class[]::new);

  Method sourceMethod = Main.class.getMethod("addOne", Number.class);
  Class<?>[] sourceParameters = Stream.of(sourceMethod.getParameters()).map(p -> p.getType()).toArray(Class[]::new);

  MethodHandles.Lookup lookup = MethodHandles.lookup();
  CallSite site = LambdaMetafactory.metafactory(lookup, //
      lambdaMethod.getName(), //
      MethodType.methodType(lambdaMethod.getDeclaringClass()), //
      MethodType.methodType(lambdaMethod.getReturnType(), lambdaParameters), //
      lookup.unreflect(sourceMethod), //
      MethodType.methodType(sourceMethod.getReturnType(), sourceParameters));

  AddOneLambda addOneLambda = (AddOneLambda) site.getTarget().invoke();
  System.out.println("1 + 1 = " + addOneLambda.addOne(1));
}

I receive the following exception from metafactory:

LambdaConversionException: Type mismatch for dynamic parameter 0: class java.lang.Number is not a subtype of class java.lang.Integer

I don't understand this. Passing an Integer to the AddOneLambda should always be fine, because the underlying addOne method can accept Integers as part of it's Number signature - so I believe this configuration should be "safe".

On the other hand, when I execute the above with this change:

public static int addOne(Integer base) {
  return base.intValue() + 1;
}

public interface AddOneLambda {
  public int addOne(Number base);
}

The metafactory allows now this without exception, but it doesn't seem right. I can pass any kind of Number to AddOneLambda, even though the underlying method can only handle Integers - so I believe this configuration to be "unsafe". Indeed, if I now call addOneLambda.addOne(1.5) I receive an exception for inability to cast Double to Integer.

Why then is my initial code not allowed, while the change which ultimately allows for invalid types to be passed ok? Is it something to do with the values I'm passing to metafactory, is metafactory incorrectly checking the types, or does this prevent some other kind of situation I haven't considered? If relevant, I'm using JDK 17.0.3.





samedi 4 juin 2022

Type.GetField on array field returns null

I'm trying to get an array field from class using Reflections. On a simple field it works, on Array it doesn't.

This is the class

public abstract class Condition : ScriptableObject
{
    public string Name;
    public virtual bool IsVerified() { return false; }
}

public class ExampleScript : MonoBehaviour
{
    [SerializeField] Condition _condition = null;
    [SerializeField] Condition[] _conditions = new Condition[0];
}

[CustomPropertyDrawer(typeof(Condition))]
public class ConditionPropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        Type propertyType = GetPropertyType(property);

        EditorGUI.EndProperty();
    }

    private Type GetPropertyType(SerializedProperty property)
    {
        Type parentType = property.serializedObject.targetObject.GetType();
        Debug.Log($"{parentType} => {property.propertyPath}");
        FieldInfo fi = parentType.GetField(property.propertyPath, BindingFlags.NonPublic | BindingFlags.Instance);
        Debug.Log(fi);
        return fi.FieldType;
    }
}

This is where I'm getting Fields:

Type parentType = property.serializedObject.targetObject.GetType();
Debug.Log($"{parentType} => {property.propertyPath}");
FieldInfo fi = parentType.GetField(property.propertyPath, BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Log(fi);

The Debug prints (Condition var):

ExampleScript => _condition
MyFullNameSpace.Condition _condition

The Debug prints (Condition[] var):

ExampleScript => _conditions.Array.data[0]
Null

Why it doesn't return right FieldInfo?
Thanks in advance





jeudi 2 juin 2022

reset static field to their initial value using reflexion in java

I use in my project a lib with some class with a lot of static field and other stuffs, who are indirectly updated and consulted at runtime in my app. I can't update or ignore or mock this class.

How can I re-execute the method who initialise the static field of a class?

I'm currently writing test in my app, which trigger this class. I want the static field of this class to be at their init state each time I start my app.

The issue is, setting manualy those static field is not possible, it would be too complexe. I need them to be put at their initial state "automaticaly"

I can't change anything to the code of the class, because it's in a lib.

Any idea how I can do that? With reflexion, maybe?





How to get static properties from base type via reflection

I try to get static properties from a base type via reflection. There are many questions regarding this topic on this side, but they all focus on getting non static properties of a base type or static properties from the target type.

public class A
{
    public static string STATIC_BaseProp => "STATIC_BaseProp"; //<-- I want this
    public string BaseProp => "BaseProp";
}

public class B : A
{
    public static string STATIC_Prop => "STATIC_Prop";
    public string Prop => "PROP";
}

static void Main(string[] args)
{
    var type = typeof(B);
    foreach (var propertyInfo in type.GetProperties())
    {
        Console.log(propertyInfo);
    }
}

Output:

System.String STATIC_Prop
System.String Prop
System.String BaseProp

This seems to only adress the static properties of the target type and the non static properties of the target type and the base type. But i want the static property of the base type (STATIC_BaseProp)

Does anyone know how to do this?





mercredi 1 juin 2022

Dynamically calling decorated functions in sequence [duplicate]

I want to expose an api endpoint that allows a user to submit a payload w/ a sequence of functions to be called (pre-defined), along with their parameters.

Also, these functions are wrapped with decorators.

What is the proper way of accessing a function by name in python?

example payload:

{
    "step1": {
        "fn": "function_1",
        "params": {
            "input_file": "example.txt"
        }
    },
    "step2": {
        "fn": "function_2",
        "params": {
            "y": 2
        }
    }
}

In this scenario I should have python run function_2(function_1("example.txt")``, kwargs=**step2["params"])





Why do the following code prints the stack trace and why is a.toString() in the return statement not giving an error or exception?

Following is the complete code -

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;

class A2<T> {
    T ob;
    A2(T ob) {
        this.ob = ob;
    }
    @Annos(str="T example")
    T retob() {
        return ob;
    }
    @Override
    public String toString() {
        Annotation a = null;
        try {
            Class<?> c = this.getClass();
            Method m = c.getMethod("retob");
            a = m.getAnnotation(Annos.class);
        }catch(NoSuchMethodException NSMe) {
            NSMe.printStackTrace();
        }
        return a==null?"EMPTY":a.toString();
    }
    public static void main(String args[]) {
        System.out.println(new A2<Integer>(2).toString());
    }
}

@Retention(RetentionPolicy.RUNTIME)
@interface Annos {
    String str();
}

If I have override the toString() method then how can a.toString() in the return statement as well as in the main method work?

Here is the output -

java.lang.NoSuchMethodException: A2.retob()
        at java.base/java.lang.Class.getMethod(Class.java:2227)
        at A2.toString(A2.java:20)
        at A2.main(A2.java:28)
EMPTY

Why is it not able to get the method retob?