samedi 29 juillet 2023

Attempt to change static non final field throws IllegalArgument Exception

Class that has private static non final field

package sample;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {
   private static Logger logger = LoggerFactory.getLogger(App.class);

   public void doSomething() {
      logger.error("Cannot do something");
   }
}

Attempt to set this field through reflection

package sample;

import org.apache.logging.log4j.core.Logger;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;

import static org.mockito.Mockito.mock;

public class AppTest {

    @Test
    public void doSomething() throws Exception {
        App app = new App();

        Logger mockedLogger = mock(Logger.class);

        ReflectionTestUtils.setField(App.class, "logger", mockedLogger);
    }
}

results in IllegalArgumentException

Can not set static org.slf4j.Logger field sample.App.logger to org.apache.logging.log4j.core.Logger$MockitoMock$1185285221
java.lang.IllegalArgumentException: Can not set static org.slf4j.Logger field sample.App.logger to org.apache.logging.log4j.core.Logger$MockitoMock$1185285221
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeStaticObjectFieldAccessorImpl.set(UnsafeStaticObjectFieldAccessorImpl.java:79)
    at java.lang.reflect.Field.set(Field.java:764)
    at org.springframework.util.ReflectionUtils.setField(ReflectionUtils.java:633)

According to JavaDocs of invoked method

https://docs.spring.io/spring-framework/docs/5.2.20.RELEASE/javadoc-api/

Set the static field with the given name on the provided targetClass to the supplied value.

setting static field is supported.





vendredi 28 juillet 2023

Reflective access to *** is forbidden when targeting API 33 and above

I need to access the bootClassPathUrlHandlers in the VMClassLoader class using reflection but I am getting this error: "Reflective access to bootClassPathUrlHandlers is forbidden when targeting API 33 and above".

If I ignore it and run the app anyway I get this runtime exception: java.lang.NoSuchFieldException: No field bootClassPathUrlHandlers in class Ljava/lang/VMClassLoader; (declaration of 'java.lang.VMClassLoader' appears in /apex/com.android.art/javalib/core-libart.jar)

This is the part of code that I am using:

            Class cVMClassLoader = Class.forName("java.lang.VMClassLoader");
            Field vHandlers = cVMClassLoader.getDeclaredField("bootClassPathUrlHandlers");
            vHandlers.setAccessible(true);

            Object[] handlers = (Object[]) vHandlers.get(null);

How can I access it?





Find Java annotations via reflection for Kotlin getter

We have a wrapper class for checking the Android SDK version, and it uses the ChecksSdkIntAtLeast annotation. Here's a trimmed example of the class with just one getter and the logging removed:

class DeviceApi(
    private val deviceOsVersion: Int
) {
    @get:ChecksSdkIntAtLeast(api = Build.VERSION_CODES.M)
    val isApi23AndAbove get() = deviceOsVersion >= Build.VERSION_CODES.M
}

We have tests for the getter itself, but I was hoping to write tests to verify that the getter also has the annotation in place with the correct value, to avoid the compiler warnings that show up if it isn't included. However, no matter what I try, I can't seem to find the annotation via reflection.

Here's two basic examples that work if I do this for a Kotlin annotation class annotation that just don't find the public @interface annotations provided by androidx.annotation:

@Test
fun kotlin_reflection_example() {
    assertThat(DeviceApi::isApi23AndAbove.getter.hasAnnotation<ChecksSdkIntAtLeast>()).isTrue
}

@Test
fun java_reflection_example() {
    assertThat(DeviceApi::isApi23AndAbove.javaGetter!!.getAnnotation(ChecksSdkIntAtLeast::class.java)).isNotNull
}

I've also tried various examples I've seen online for looking for members and methods from the class and debugged to inspect the state of various things, but I've been unable to get any of the code to see the annotation. I want to know if I'm missing something obvious or if I found a scenario that just isn't supported by kotlin-reflect - and if so, if there's an alternative.





jeudi 27 juillet 2023

weird Json deserialization on a read-only property in C#

Can somebody explain how does it work? I even use reflection to set value to B, but it said B dont have a set value. How Newtonsoft.Json make this work?

public class A
{
    private int a = 10;
    public int B => a;
}

var a = new A();
var json = JsonConvert.SerializeObject(a);//json={"B":10}

//my expectation: this will have error, because B only have getter, dont have setter
//in reality: this run OK, and aa.B = aa.a = 10
var aa = JsonConvert.DeserializeObject<A>(json);




mercredi 26 juillet 2023

How could I run the constructor of all the classes in a package without knowing the names of all of the classes?

I want to make a class that would run the constructor of each class in the package, excluding itself of course. So I would be able to add another class to the package and the constructor of the class would be run without having to go and explicitly call it in the main class. Its for a minecraft plugin so its being compiled into a jar and run that way chat gpt said that made some kind of difference.

I've tried to get the package name and use that to get a path which would look for all of the files using a class loader. I'm able to get a list of the classes in a different project but not in the plugin.

public static List<Class<?>> getClassList() {
        List<Class<?>> classList = new ArrayList<>();
        String packageName=Loader.class.getPackage().getName();
        String packagePath = packageName.replace('.', '/');

        try {
            java.lang.ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader == null) {
                throw new ClassNotFoundException("Unable to get class loader.");
            }

            // Get all resources (files and directories) in the package directory
            java.util.Enumeration<java.net.URL> resources = classLoader.getResources(packagePath);
            while (resources.hasMoreElements()) {
                java.net.URL resource = resources.nextElement();
                if (resource.getProtocol().equals("file")) {
                    // If the resource is a file, get class objects
                    getClassObjectsFromFile(packageName, resource.getPath(), classList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return classList;
    }

    private static void getClassObjectsFromFile(String packageName, String filePath, List<Class<?>> classList)
            throws ClassNotFoundException {
        java.io.File directory = new java.io.File(filePath);
        if (directory.exists()) {
            java.io.File[] files = directory.listFiles();
            if (files != null) {
                for (java.io.File file : files) {
                    if (file.isFile() && file.getName().endsWith(".class")) {
                        String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                        Class<?> clazz = Class.forName(className);
                        classList.add(clazz);
                    }
                }
            }
        }
    }

Thanks





mardi 25 juillet 2023

Get Parameters Pass into an method from an attribute

I have an attribute that I'm placing on a method:

[MyAttribute]
public void MyMethod(SomeClass prop) {
    //...
}

Lets say I'm invoking the method like so:

MyMethod(new SomeClass() { MyProp = 354});

I would like My attribute to be able to read in the properties which are passed into the method.

How can I Obtain access to the parameters of the method which the attribute is on. I would Imagine the call would look something like so:

var callStack = GetCallStack().
callStack.Pop();
var methodFrame = callStack.Current;
methodFrame.GetParameterAtIndex<SomeClass>(0);

Is there a way I can do this from the internals of the attribute?





lundi 24 juillet 2023

Is there an implicit type casting when using Functional Interfaces in Java?

I wrote the following Java code and expected it to not compile but it did and also executed counterintuitively. I am using Java 17.

TestFunctionExecutor.java

@FunctionalInterface
public interface TestFunctionExecutor{
    void execute();
}

TestClass.java

public class TestClass{
    public static void main(String... args) {
        TestClass test = new TestClass();
        test.wrapper(test::sampleFunction);
    }
    
    public void sampleFunction() {
        System.out.println("Inside sampleFunction");
    }

    public void wrapper(TestFunctionExecutor method) {
        System.out.println("Before method execution");
        method.execute();
        System.out.println("After method execution");
    }
}

Output -

Before method execution
Inside sampleFunction
After method execution

I thought since wrapper expects an argument of type TestFunctionExecutor and I am passing one of type TestClass the compilation should fail. I used a debugger and looks like method is a TestClass$$Lambda$1... at runtime. This confuses me and I have a few questions -

  1. What is the type of test::SampleFunction? Is it not TestClass or something like TestClass$$sampleFunction...? I am unable to deduce this with a debugger.
  2. Why were there no errors here? Looks like the types somehow became compatible, how?
  3. How does execute know what code to execute?
  4. Is this good code? My aim is to wrap a function so that some code runs before and after it.

Thanks!





dimanche 23 juillet 2023

How Using Golang Reflect Type to Instantiate Generic Type Seeding From It

Having a generic interface

type G[T any] interface {
...
}

and reflect.Type t, how to instantiate another reflect.Type which would represent actually G[t]

Eventually the t it self should be matched against G[t]

func ImplementsG(t reflect.Type) bool {
    var gType reflect.Type = ... // instantiate(G, t)

    return t.Implements(gType)
}




How to register method for runtime reflection with GraalVM?

I am trying to get an existing Java application running with GraalVM. Now I have encountered an issue i don't know how to solve. I was able to successfully create a native image. However I had to create a reflection configuration like this to overcome the "Warning: Reflection method java.lang.Class.getMethod invoked" message during the compile phase:

[
  {
    "name": "java.lang.Class",
    "queryAllDeclaredConstructors": true,
    "queryAllPublicConstructors": true,
    "queryAllDeclaredMethods": true,
    "queryAllPublicMethods": true,
    "allDeclaredClasses": true,
    "allPublicClasses": true
  },
  {
    "name": "org.apache.logging.log4j.message.DefaultFlowMessageFactory",
    "queryAllDeclaredConstructors": true,
    "queryAllPublicConstructors": true,
    "queryAllDeclaredMethods": true,
    "queryAllPublicMethods": true,
    "allDeclaredClasses": true,
    "allPublicClasses": true
  }
]

I've added the second entry, because my native image was throwing a method-not-found error for org.apache.logging.log4j.message.DefaultFlowMessageFactory.<init>

When I run my native image now, I get the following error:

Exception in thread "main" org.graalvm.nativeimage.MissingReflectionRegistrationError: The program tried to reflectively invoke method public org.apache.logging.log4j.message.DefaultFlowMessageFactory() without it being registered for runtime reflection. Add it to the reflection metadata to solve this problem. See https://www.graalvm.org/latest/reference-manual/native-image/metadata/#reflection for help.
    at org.graalvm.nativeimage.builder/com.oracle.svm.core.reflect.MissingReflectionRegistrationUtils.forQueriedOnlyExecutable(MissingReflectionRegistrationUtils.java:97)
    at java.base@17.0.8/java.lang.reflect.Constructor.acquireConstructorAccessor(Constructor.java:74)
    at java.base@17.0.8/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:496)
    at java.base@17.0.8/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base@17.0.8/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347)
    at java.base@17.0.8/java.lang.Class.newInstance(DynamicHub.java:645)
    at org.apache.logging.log4j.spi.AbstractLogger.createDefaultFlowMessageFactory(AbstractLogger.java:240)
    at org.apache.logging.log4j.spi.AbstractLogger.<init>(AbstractLogger.java:141)
    at org.apache.logging.log4j.status.StatusLogger.<init>(StatusLogger.java:141)
    at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:91)
    at org.apache.logging.slf4j.Log4jMarkerFactory.<clinit>(Log4jMarkerFactory.java:36)
    at org.apache.logging.slf4j.SLF4JServiceProvider.initialize(SLF4JServiceProvider.java:53)
    at org.slf4j.LoggerFactory.bind(LoggerFactory.java:183)
    at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:170)
    at org.slf4j.LoggerFactory.getProvider(LoggerFactory.java:455)
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:441)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:390)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:416)
    at app.Main.<clinit>(Main.java:12)

The error message implies that I might be able to solve this problem my registering this method for runtime reflection.

OK, But how? I couldn't find anything helpful in the documentation.

Any ideas? Are there any examples I might have missed?





vendredi 21 juillet 2023

Setting Realm Object property / relation dynamically

I am using realm in a react native project in typescript, and I would like to assign a relation object to another object dynamically.

For instance, instead of doing myUserObject.profile = myProfileObject I would like to do something like that : myUserObjectTypedAsRealmObject[relationName] = theOtherRealmObject.

Is it possible to make something dynamic like that ? I also tried to change type of relationName from string to keyof Realm.Object but that also didn't work.





jeudi 20 juillet 2023

class.isInstance returns false but should report true

I have a library, which includes the following class:

@RequiredArgsConstructor
public class TypeConsumer<T> {

    private final Class<T> clazz;
    private final Consumer<T> consumer;

    public void consume(Object object) {
        if (clazz.isInstance(object)) {
            this.consumer.accept((T) object);
        }
    }
}

In a other project I have a Class. Lets call it A and an other class B. B extends A. In this other project I use to following code

B b = new B();
TypeConsumer<A> consumer = new TypeConsumer<>(A.class, System.out::println)
consumer.consume(b);

Every time. the check is false, but I don't know why. I tested clazz.isAssignableFrom(b.getClass()) too, but the check is always false, but it should be true, because as I said, B extends A

What do I have to change or what did I wrong, to let the check work correctly





How to get method annotation value

I am writing a plugin for parsing a jar archive, using the url classloader, I get reflective access to the classes of this archive, I have annotation names by which I can find the classes corresponding to them in the bytecode (for obvious reasons, I do not have access to the annotation class itself from the code that is currently parsing this jar), I'm sure there is some dirty trick to do this, please help

for example what i am doing in nutshell:

Path pathToJar = Paths.get("/a/b/c/Application.jar");

List<Class<?>> allJarClasses = loadAllJarClasses(pathToJar);

String annotationName = "MyAnnotation";

getValueFromAnnotationWithName(annotationName, allJarClasses);

---

public String getValueFromAnnotationWithName(String annotationName, List<Class<?>> classes) {
    classes.forEach(cl -> {
        Method[] methods = ...getMethods
        for(Method m : methods) {
            Annotations[] annotations = ...getAnnotations from method
            for (Annotation a: annotations) {
               if (a.annotationType().getName().matches(".*" + annotationName)) {
                     return getValueFromAnnotation("someValueName", a); <- here i need help;
               }
            }
        }
    });
}

Update: i can get values while debugging in intellij idea enter image description here

also if do this:

annotationMethod.toString()

i can get this:

@ru.sparural.kafka.annotation.KafkaSparuralMapping(value="file/create")





mercredi 19 juillet 2023

Create a Moq Mock from System.Type

Is it possible to create a Mock from a System.Type variable?

We are converting projects from Rhino to Moq. In Rhino we could previously do this:

var type = typeof(/* Some type */);
MockRepository.GenerateStub(type);

The creation methods in Moq are (at least as far as I have found) all based on generic type parameters instead of System.Type.

Unfortunately there are a lot of different types for which a Mock is needed packed in different infrastructure layers and handed over as a variable of System.Type to the point where the Mock is created. So converting all this to generic is very cumbersome if it can be done at all.





lundi 17 juillet 2023

How to determine whether a reference-based generic parameter is nullable [duplicate]

Generally, using C# reflection I've been able to get every detail that's ever been needed about a type. I've recently encountered a specific use-case that I have not been able to reflect: reference-based generic parameter nullability.

For example, given:

    public class ReflectMe
    {
        public List<long?> Ids0 { get; set; } = new List<long?>();

        [NullParam(true)]
        public List<String?> Names0 { get; set; } = new List<String?>();

        public List<long?>? Ids1 { get; set; } = new List<long?>();

        [NullParam(true)]
        [NullParam(true)]
        public List<List<String?>?>? Names1 { get; set; } = new List<List<string?>?>();
    }

The Ids0 and Ids1 can be reflected (via either Nullable.GetUnderlyingType or NullabilityInfoContext) since the inner long is a value-type. However, Names0 's String cannot be reflected, and Names1's inner List and String cannot be reflected.

The NullParam attribute was created as a work-around but is obviously not ideal.

Using C# v 11 (.NET 7.0) with Nullable enabled.

Any ideas about how this can be achieved?





Why using AssemblyLoadContext.LoadFromAssemblyPath does not let me unload it later?

I am loading an assembly dynamically at run-time in .net 7 WPF app..

This context loader lets me to unload it later (see the MemoryStream): (taken from here: https://github.com/dotnet/runtime/issues/13226)

    public class CollectableAssemblyLoadContext : AssemblyLoadContext
    {
        private bool disposedValue;

        public CollectableAssemblyLoadContext(string name) : base(name, true) { }

        protected override Assembly Load(AssemblyName assemblyName) => null;

        public Assembly Load(byte[] rawAssembly)
        {
            using (var memoryStream = new MemoryStream(rawAssembly))
            {
                var assembly = LoadFromStream(memoryStream);
                return assembly;
            }
        }
    }

And this throws "not collectible assembly" exception on unload: (taken from here: https://learn.microsoft.com/en-gb/dotnet/core/tutorials/creating-app-with-plugin-support)

    public class PluginLoader : AssemblyLoadContext
    {
        private AssemblyDependencyResolver resolver;

        public PluginLoader(string pluginPath)
        {
            resolver = new AssemblyDependencyResolver(pluginPath);
        }

        protected override Assembly Load(AssemblyName assemblyName)
        {
            string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
            if (assemblyPath != null)
            {
                return LoadFromAssemblyPath(assemblyPath);
            }

            return null;
        }
    }

Why? Is it by design or am I doing something wrong?





dimanche 16 juillet 2023

Having trouble adding fields to a SpringBoot entity

Hello I am a beginner at SpringBoot and I am having trouble using Java reflection to validate my min and max fields. I have a Part class that with each part object having different min and max values for the inventory and I want to access those values at runtime in the validation part of my SpringBoot application.

This is the relevant code for the Part class:

@ValidInvRange
    int inv;

    int min;
    int max;

I want to know how I can access the integer values using reflection in a Validation class. I have been unable to figure it out so far.

So far I've tried for each value to this-

Field inv = Part.class.getDeclaredField("inv");
int inventory = (int) inv.get(inv);




Check if Collection of DTOs sorted by a given field

I have to write tests for a pagination and sorting GET ALL endpoint that I have. The following is the simple DTO that I am working with:

public class TransactionDto {
  private Long id;
  private Long sourceAccountId;
  private Long targetAccountId;
  private BigDecimal amount;
  private Currency currency;
}

Of importance to this discussion is that all of those fields are Comparable, including the type Currency, which is an enum I have created with about 300 different currency symbols.

Now, I want to ensure that a REST controller endpoint has returned a Collection of these TransactionDto instances in a sorted manner. After reading here I learned of Guava's Comparators class and, specifically, the isInOrder method (doc link).

I have to begin with the field name of TransactionDto to sort by, and I also have this simple SortOrder enum to designate ascending or descending sort order:

public enum SortOrder {
    ASC, DESC
}

This is what I have so far, and I am stuck on the fact that the Method.invoke() method returns raw Object instances.

private boolean collectionIsSortedByFieldInGivenDirection(Collection<TransactionDto> transactionDtos,
                                                            String sortByField, SortOrder sortOrder){
    return Comparators.isInOrder(transactionDtos, (t1, t2) -> compareFieldsInGivenOrder(t1, t2, sortByField, sortOrder));
}

private int compareFieldsInGivenOrder(TransactionDto transactionOne, TransactionDto transactionTwo,
                                        String sortByField, SortOrder sortOrder){
    try {
      PropertyDescriptor propertyDescriptor = new PropertyDescriptor(sortByField, TransactionDto.class);
      Method appropriateGetter = propertyDescriptor.getReadMethod();
      Object transactionOneValue = appropriateGetter.invoke(transactionOne);
      Object transactionTwoValue = appropriateGetter.invoke(transactionTwo);
      // Not much I can do with raw Objects...
    } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
      throw new RuntimeException(e.getMessage());
    }
}

I need to somehow retrieve variables of the appropriate type, which, as shown above, will be a type whose instances are Comparable with instances of the same type. I have also fiddled a bit with the Field.getType() method after reading through this answer but I haven't had much luck. Any ideas?





vendredi 14 juillet 2023

How to retrieve the properties of a NextJS Component in runtime?

I have a bunch of NextJS components such as this one:

"use client";

type Props = {
  title: string;
  subtitle: string;
};

export default function HeaderComponent(props: Props) {
  return (
    <div>
      <h1>{props.title}</h1>
      <h2>{props.subtitle}</h2>
    </div>
  );
}

I am trying to find a way to extract the component props in run-time to an array of names. in the case above I'm looking to get the response of:

["title", "subtitle"]

I thought I can achieve this by following the NextJS docs on lazy loading and dynamic components but so far ended up with ComponentPropsType without knowing how to convert it to an array of strings. what I have so far is:

const Component = dynamic(() => import("../components/header"), {
  ssr: false,
  loading: (lodaingProps) => {
    return <p>Loading...</p>;
  },
});
type ComponentPropsType = React.ComponentProps<typeof Component>;

Can someone please direct me on the right way to do this? at this point I'm not even sure this is feasible. based on some readings I found that this type of data may not even available in run-time. is that true?





Update entity related objects using reflection

hy everyone. i am trying to update the entity related objects using reflection. my current appproach is to look for parent properties of entity. if incoming property name is found then get its value. if not then get all the relatedObjects. and start looking for propertyName. if property name is found then return the propertyInfo with the related Object. my current object looks like this

`class UserArea{
        public int Id { get; set; }

        public Department Department { get; set; }
        public int DepartmentId  { get; set; }
        
        public Area Area  { get; set; }
        public int AreaId  { get; set; }
        public User User { get; set; }
        public string UserId { get; set; }
}`

i receive the parameters to update with thier values in dictionary<string,object> the problem is i dont receive complete object with all related properties filled. i.e if i to update User name property then i would receive {fullName: "userName" } in dictionary. now its upto me to look up for property in all the related objects. but that is not the problem. the problem when i found the property i am unable to set its value in the parent entity object because its null there and c# does not set properties that way.

this is what i have tried. it works fine and finds the property in related objects. but does not sets the propery back in parent entity object

        private async Task<TEntity?> EditObject<TEntity>(int key, Dictionary<string, string> properties)
        {
            if (key <= 0 || properties == null)
            {
                throw new ArgumentException("Invalid input parameters");
            }

            var setMethod = typeof(UsafeDbContext).GetMethod(nameof(UsafeDbContext.Set), Type.EmptyTypes);
            var dbSet = setMethod.MakeGenericMethod(typeof(TEntity)).Invoke(_context, null);

            var filteredResult = ((IQueryable<TEntity>)dbSet).AsEnumerable().Where(entity => entity.GetType().GetProperty("Id").GetValue(entity).ToString() == key.ToString());

            var entityObject = filteredResult.FirstOrDefault();


            var entityKeys = typeof(TEntity).GetProperties();

            foreach (var propKey in properties.Keys)
            {
                var propertyName = propKey.ToLower(); // Modify to handle case sensitivity if desired

                var (propertyInfo, relatedObject) = FindProperty(entityKeys, propertyName, entityObject).Value;
                if (propertyInfo != null)
                {
                    try
                    {
                        var propertyType = propertyInfo.PropertyType;
                        var propertyValue = Convert.ChangeType(properties[propKey], propertyType);
                        if (propertyType.IsEnum)
                        {
                            propertyValue = Enum.Parse(propertyType, properties[propKey]);
                        }
                        propertyInfo.SetValue(entityObject, propertyValue);
                    }
                    catch (Exception ex)
                    {
                        // Properly handle or log the exception
                        Console.WriteLine($"{ex.Message}\r\n {ex.StackTrace}");
                    }
                }

                else if (relatedObject != null)
                {
                    var relatedPropertyInfo = relatedObject.GetType().GetProperty(propertyName);
                    if (relatedPropertyInfo != null)
                    {
                        try
                        {
                            var propertyType = relatedPropertyInfo.PropertyType;
                            var propertyValue = Convert.ChangeType(properties[propKey], propertyType);
                            if (propertyType.IsEnum)
                            {
                                propertyValue = Enum.Parse(propertyType, properties[propKey]);
                            }
                            relatedPropertyInfo.SetValue(relatedObject, propertyValue);
                        }
                        catch (Exception ex)
                        {
                            // Properly handle or log the exception
                            Console.WriteLine($"{ex.Message}\r\n {ex.StackTrace}");
                        }
                    }
                }
            }

            return entityObject;
        }


        private (PropertyInfo PropertyInfo, object RelatedObject)? FindProperty(PropertyInfo[] entityKeys, string propertyName, object entityObject)
        {
            var topProps = entityKeys
                .FirstOrDefault(x =>
                    x.Name.ToLower() == propertyName && x.GetCustomAttribute(typeof(IgnorePropertyAttribute)) is null);
            if (topProps is not null)
                return (topProps, null);

            var relatedObjects = entityKeys
                .Where(p => p.PropertyType.IsClass && p.PropertyType.Namespace == "usafe.Models")
                .ToList();

            foreach (var relatedObject in relatedObjects)
            {
                var relatedEntity = relatedObject.PropertyType.GetProperties().FirstOrDefault(x => x.Name.ToLower() == propertyName);
                if (relatedEntity != null)
                {
                    if (relatedEntity.GetCustomAttribute(typeof(IgnorePropertyAttribute)) is null)
                    {
                        var relatedPropertyValue = relatedObject.GetValue(entityObject);
                        return (relatedEntity, relatedPropertyValue);
                    }
                }
            }
            return null;
        }




Composing Queryable with "ThenInclude" with Dynamic Generic Arguments

Environment: .NET 6, EF 6.0.19

This might not be possible, but I am trying to use reflection to generate a query for my generic types which crawls the navigations from the root type and includes/thenincludes all related types.

Getting the includes (first-order-relationships) to work is pretty trivial and works:

// Get all the navigation properties for the type so we can include them
IEnumerable<INavigation> navigations = _dbContext.Model.FindEntityType(typeof(T)).GetNavigations();

// Add include clauses for each navigation property so we get the full model
foreach (INavigation prop in navigations)
{
    query = query.Include(prop.Name);
}

where query is IQueryable<T> from System.Linq.

However, ThenInclude() is a method on IIncludableQueryable<T, U> where U is some property in the navigation path from T. However, because we don't know U at compile-time, we need to use reflection to determine the type and

  1. create a generic type for the IIncludableQueryable
  2. Create the expression for the new part of the query and
  3. amend the query (or return a new query based on the original query)

However, using Activator to make an IIncludableQueryable fails because of a perceived type mismatch during creation; however, what I'm unclear is on where the type massaging would normally happen in a standard ThenIncludes call. Below is an example of what I'm running and where it's failing (ignore that this doesn't cover all edge cases and doesn't recurse properly)

private IQueryable<T> AddNavigationProperties<T>(IQueryable<T> query)
        where T : class, IMyInterface
{
    // Get all the navigation properties for the type so we can include them
    IEnumerable<INavigation> navigations = _dbContext.Model.FindEntityType(typeof(T)).GetNavigations();

    // Add include clauses for each navigation property so we get the full model
    foreach (INavigation prop in navigations)
    {
        query = query.Include(prop.Name);

        if (prop.ClrType.IsGenericType && prop.ClrType.IsCollection())
        {
            var propNavs = _dbContext.Model.FindEntityType(prop.ClrType.GetGenericArguments()[0]).GetNavigations();
            var genericType = prop.ClrType.GetGenericArguments()[0];

            foreach (INavigation nav in propNavs)
            {                    
                Type delegateType = typeof(Func<,>).MakeGenericType(genericType, nav.ClrType);
                ParameterExpression parameter = Expression.Parameter(genericType, nav.Name);
                MemberExpression memberExpression = Expression.Property(parameter, genericType.GetProperty(nav.Name));
                LambdaExpression expression = Expression.Lambda(delegateType, memberExpression, parameter); // Create the expression that defines how we access this property from the previous entity

                // Make the types we will need for creating the new query instance
                var enumerableType = typeof(IEnumerable<>).MakeGenericType(nav.ClrType);
                var includableType = typeof(IncludableQueryable<,>).MakeGenericType(typeof(T), nav.ClrType);

                // ==== THIS LINE FAILS ==== 
                var includable = Activator.CreateInstance(
                        includableType,
                        // This is the pattern used for resolving the constructor parameter in EntityFrameworkQueryableExtensions
                        query.Provider is EntityQueryProvider ?
                            query.Provider.CreateQuery<T>(
                                Expression.Call(
                                    instance: null,
                                // This static MethodInfo is based on the one in EntityFrameworkQueryableExtensions
                                method: ThenIncludeAfterEnumerableMethodInfo.MakeGenericMethod(typeof(T), enumerableType, nav.ClrType),
                                arguments: new[] { query.Expression, expression }
                            ))
                        : query);
                }
            }
        }
    }

    return query;
}

The error that occurs on the failing line is essentially

Expression of type 'System.Linq.IQueryable[T] cannot be used for parameter Microsoft.EntityFrameworkCore.Query.IIncludableQueryable[T, TPreviousEntity, U] (Parameter: 'arg0')

However, it's unclear to me why that expression is not an acceptable parameter. From reading the file definitions in EF it seems like that would be the exact expression I would need.

FWIW here is the call signature of the "ThenIncludes" I am trying to invoke:

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
    this IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>> source,
    Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)
    where TEntity : class




jeudi 13 juillet 2023

C# Recursion using reflection on a where type constrain

I'm trying to do recursion through a class but I can't see how I can invoke it with a type constrain.

My problem is mainly I don't know how to invoke the recursion and pass the property type on the Analyze call.

Here's my code:

public class recursor {
public string Analyze<T>() where T : class, new() 
    {

        StringBuilder sb = new StringBuilder();

        T t = new T();

        var propList = t.GetType().GetProperties();

        foreach (var prop in propList)
        {
            System.TypeCode propertyTypeCode = Type.GetTypeCode(prop.PropertyType);
            if (prop.PropertyType.IsClass)
            {
                // THIS IS WHAT I CAN'T FIGURE IT OUT
                // sb.Append(this.Analyze());
            }
            else
            {
                sb.Append("not a class");
            }
        }
        return sb.ToString();
    }
  }


  public class A {}
  public class B {}
  public class C {}
  
  public class _container {
    public A _a;
    public B _b;
    public C _c;
  }

  public void main() {

   var r = new recursor();
   var s = r.Analyze<_container>();

  }




mercredi 12 juillet 2023

LambdaMetaFactory with Generic Static Methods?

So I'm creating a library that allows users to pass a Class<?> and collect all static methods with a specific annotation (and other criteria, such as a certain parameter count and types) and convert them into lambda FunctionalInterfaces that my library will use internally for processing.

For example:

Say I have the following class tree:

public abstract class AbstractParent {
  
  public String sayHi() {
    return getClass().getName() + " instance says hi!";
  }

}

with subclasses:

public class ChildOne extends AbstractParent {

  public int childOneSpecialMethod() {
    return 2558445;
  }
}
public class ChildTwo extends AbstractParent {

  public int childTwoSpecialMethod() {
    return 484848;
  }
  
}

My library allows for users to annotate a class's static methods with the following annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProcessAnnotation {}

with the following rules: the static method first parameter be an instance of AbstractParent, and its second parameter must be a String, and must return a String. So, something like this:

public class GeneralProcessor {
  
  @ProcessAnnotation
  public static String easyProcessing(ChildOne one, String otherArg) {
    //Some code
    System.out.println(" === In processing for ChildOne types");
    return otherArg + one.toString();
  }

  @ProcessAnnotation
  public static String easyProcessing(ChildTwo two, String otherArg) {
    //Some code
    System.out.println(" === In processing for ChildTwo types");
    return otherArg + two.toString();
  }
}

On the library-side of things, I want to collect all these methods so that I can use them for some processing while doing it in a relatively fast manner and I found that MethodHandles and LambdaMetaFactory is the best way to do this.

Specifically, I want to invoke these collected methods using my own FunctionalInterface :

@FunctionalInterface
public interface ProcessInterface<T extends AbstractParent> {
  
  public String process(T obj, String extraArg);
}

So far, what I've tried is something like this:

public static List<ProcessInterface<? extends AbstractParent>> generate(Class<?> targetClass) throws Throwable {
    ArrayList<ProcessInterface<? extends AbstractParent>> processors = new ArrayList<>();

    for (Method method : targetClass.getDeclaredMethods()) {
      if (method.isAnnotationPresent(ProcessAnnotation.class) &&
          method.getParameterCount() == 2 && 
          AbstractParent.class.isAssignableFrom(method.getParameterTypes()[0]) &&
          method.getParameterTypes()[1] == String.class) {
        
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle handle = lookup.unreflect(method);
        CallSite callSite = LambdaMetafactory.metafactory(lookup, 
                                                          "process", 
                                                          MethodType.methodType(ProcessInterface.class), 
                                                          MethodType.methodType(String.class, 
                                                                                method.getParameterTypes()[0],
                                                                                String.class), 
                                                          handle, 
                                                          handle.type());

        ProcessInterface<? extends AbstractParent> func = (ProcessInterface<? extends AbstractParent>) callSite.getTarget().invoke();
        processors.add(func);
      }
    }

    return processors;
  }

However, I get the following error when I actually invoke the lambda. For example:

List<ProcessInterface<? extends AbstractParent>> interfaces = generate(GeneralProcessor.class);

ChildOne childOne = new ChildOne();
interfaces.get(0).process(childOne, "");

Is there a fix to do this? Or maybe even a better way to achieve this?





mardi 11 juillet 2023

How to find the list of extension functions of a Kotlin class and its usages using reflection? [duplicate]

I have this code so far but none of the methods return the myExtensionMethod function as expected:

import kotlin.reflect.full.declaredFunctions
import kotlin.reflect.full.declaredMemberExtensionFunctions
import kotlin.reflect.full.declaredMemberExtensionProperties
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.declaredMembers

fun main() {
    println(MyEntity::class.declaredFunctions)
    println(MyEntity::class.declaredMembers)
    println(MyEntity::class.declaredMemberProperties)
    println(MyEntity::class.declaredMemberFunctions)
    println(MyEntity::class.declaredMemberExtensionProperties)
    println(MyEntity::class.declaredMemberExtensionFunctions)
}

class MyEntity(
    var id: String,
)

fun MyEntity.myExtensionMethod() {
    println("Extension")
}

This is the output:

[]
[var MyEntity.id: kotlin.String]
[var MyEntity.id: kotlin.String]
[]
[]
[]

How do I retrieve myExtensionMethod via reflection? I am trying to find all callers of this method up until the controller layer, recursively and build a graph/tree data structure.

Docs - https://kotlinlang.org/docs/extensions.html





Override ToString for pipe delimited file with the column headers in the first row

I have the following viewmodel which I am trying to create Pipe delimited string.
     public class CustomerViewModel
     {

          public string VendorCode { get; set; }


          public string MasterVendor { get; set; }


          public string ScorecardVendor { get; set; }


          public char? ImportOrDomestic { get; set; }
              
          public bool IsI2Of5Vendor { get; set; }

  This is What I have tried :

          public override string ToString()
          {

       string result = "|";

       return $"VendorCode {result} MasterVendor {result}  ScorecardVendor {result} ImportOrDomestic {result} IsI2Of5Vendor \n {VendorCode} {result} {MasterVendor}{result} {ScorecardVendor} {result} {ImportOrDomestic} {result} {IsI2Of5Vendor}";
}

Issue and expected output : With the above ToString(), I am getting column headers and values in single line, but I need VendorCode| MasterVendor|ScoreCardVendor in firstrow and then in second row its respective column values like 23|ALAN|PLASTICS.

Please suggest any solutions.





lundi 10 juillet 2023

Lambda sort using Reflection

I'm working on a project that requires the use of sorted Class lists, and I have a lambda expression that worked according to the type of class I needed to be sorted. The sorting occurs on a date field of the class itself:

Comparator<Class1> comparatorDescending = (exp1, exp2) -> exp2.getDate().compareTo(exp1.getDate());
        this.classlist2sort.sort(comparatorDescending);

However I have two, maybe more classes that need to be sorted in this way and I decided to move the lambda expression above to the parent class and make it a generic. This required a bit of work however in that I now need to pass into the parent class the type of class I'm dealing with (Class1.class), condition on that, then sort with generic. I tried the following using Reflection:

Method m = this.typeParameterClass.getDeclaredMethod("getDate");

Comparator<T> comparatorDescending = (exp1, exp2) ->
                m.invoke(exp2).compareTo(m.invoke(exp1));
this.classlist2sort((Comparator<? super T>) comparatorDescending);

Doing so gave me an error message: Unhandled exceptions: java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException to which I followed the suggested workaround of surrounding the expression with a try catch in the following manner:

Method[] input = this.typeParameterClass.getDeclaredMethods();
Method m = this.typeParameterClass.getDeclaredMethod("getDate");

Comparator<T> comparatorDescending = (exp1, exp2) -> {
            try {
                return m.invoke(exp2).compareTo(m.invoke(exp1));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
this.classlist2sort((Comparator<? super T>) comparatorDescending);

Unfortunately, doin this resulted in a Cannot resolve method 'compareTo' in 'Object' error. I am wondering now if what I'm trying to do is possible. Any help is appreciated





Hosting CLR: Calling .NET constructors/methods reflectively from C when some parameters are Enums

I have a native program that hosts the CLR (i.e. starts it up manually, gets a reference to an AppDomain, etc. - this is not C++/CLI). Within that context, I want to instantiate a FileStream object.

To my understanding, the best way of creating objects in this context is to use reflection:

SAFEARRAY* pArgs = SafeArrayCreateVector(VT_VARIANT, 0, 2);
...
BSTR assemblyName = SysAllocString(L"mscorlib");
BSTR typeName = SysAllocString(L"System.IO.FileStream");
pAppDomain->CreateInstance_3(assemblyName, typeName, VARIANT_TRUE, BindingFlags_Default, NULL, pArgs, NULL, NULL, NULL, &result);

This works fine for all sorts of other types I've tried to create; e.g. MemoryStream. But FileStream specifically has got me stumped, seemingly because FileStream expects Enum types in its constructor (e.g. System.IO.FileAccess). If I try to give it a VT_I4 (the base type of the Enum) in the place of the FileAccess parameter, it complains that it can't find the constructor (HRESULT is COR_E_MISSINGMETHOD) - which does make sense... but given Enums are value types, there's no obvious VARIANT type to use.

Is there a way to use reflection in the context of using a hosted CLR, to invoke arbitrary constructors/methods, when some of the parameters are Enums?





dimanche 9 juillet 2023

Why is the method list obtained by the reflection call inconsistent with android SDK

The system version of my phone is Android 13, and the API version is 32. I used reflection to get the method list of AccessibilityManager.java, but the list is inconsistent with SDK. For example, there is no public method getClient in the method list of reflection calls.

        try {
            Class clazz= Class.forName("android.view.accessibility.AccessibilityManager");
            Method[] methods = clazz.getMethods();
            for(Method method:methods){
                Log.e(TAG,method.getName());
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }

enter image description here

enter image description here

I tried to change the API version to 33 34, the result is the same. I'm a bit confused why they don't match





Kotlin - Get a List of classes implementing generic interface preserving type visibility

Given this generic interface:

interface Trick<I, T> {
   fun perform(input: I): T
}

I want to get a List of all classes implementing this interface, like this:

fun <I,T>loadTricks(): List<Trick<I, T>>

I already tried to use Google's Auto-Service library but all I was able to get was a list of type List<Trick<*, *>!>, which I think will be a problem as I desired to preserve the visibility on the actual type each implementation uses.

I've also came across the Reflections library, but that one is no longer being actively supported and, as such, I'd like to avoid it.

Maybe I am even going the wrong way about all this, so I'll just explain what I am aiming to achieve:

  • I want a list of all Tricks preserving the information of what Trick each of them is, the input I need to pass to "perform" and what output to expect from it.




Constructor parameter renamed to arg0 with Proguard/R8

I am using reflection to read the name of the constructor's parameters. When I enable proguard (isMinifyEnabled = true) the parameter name becomes arg0, making my reflection fail. I have tried many proguard settings, as I show next.

This is my reflection code:

(this::class as KClass<Any>).let { thisClass ->
        thisClass.firstConstructor.parameters.mapNotNull { parameter ->
            parameter.name?.let { name ->
                thisClass.memberProperties.firstOrNull { it.name == name }
            }?.let { property ->
                Argument.from(property, property.get(this), serializers)
            }
        }
    }

The proguard setting that I expected to solve this issue:

-keep class * extends my.class.package.name.Destination {
    public <init>(...);
}

I have also tried including public <fields>; and public <methods>;.
I have also tried these settings:

-keepparameternames
-keepattributes MethodParameters
-keepattributes Signature

Finally, I tried disabling shrinking with isShrinkResources = false in gradle and disabling obfuscation with -dontobfuscate in proguard, but it still renames my contructor's parameter to arg0.

Relevant project versions: kotlin 1.8.0, android gradle 7.2.2, gradle 7.5.1, Android Studio Flamingo | 2022.2.1 Patch 1.

So, how can I keep the names of the constructor's parameters so that I can match them with memberProperties?





Is it possible to convert a Function object to a byte array in dart?

I have a dart class which contains a Function member variable (which is different for each instance of the class). I need to store instances of this class in a database (such as ObjectBox), but in order to do so, I have to convert the Function to something that ObjectBox can handle.

I have seen that (using isolates) I could store the function as a string and then execute the string in a similar manner to JS eval(), but this feels like it is prone to errors and I'm hoping there's a better way of storing an actual function (not to mention isolates only working in JIT mode).

I can't see any obvious way to do this, but I'm hoping somebody here knows something I don't!





vendredi 7 juillet 2023

Intercept previous methods with class method chain conditionally in javascript

I'm just wondering if it's possible to intercept previous methods in a class chain, i have these classes

class And {
  client;
  table;
  condition;

  constructor(client, table, condition) {
    this.client = client;
    this.table = table;
    this.condition = condition;
  }

  and(anotherCondition) {
    return this.client.query(
      `SELECT * FROM "${this.table}" WHERE ${this.condition} AND ${anotherCondition};`
    );
  }
}

class Where {
  client;
  table;

  constructor(client, table) {
    this.client = client;
    this.table = table;
  }

  where(condition) {
    return this.client.query(
      `SELECT * FROM "${this.table}" WHERE ${condition};`
    );
  }
}

class Select {
  client;

  constructor(client) {
    this.client = client;
  }

  from(table) {
    return this.client.query(`SELECT * FROM "${table}";`);
  }
}

class Database {
  client;

  constructor(client) {
    this.client = client;
  }

  select() {
    return new Select(this.client);
  }
}

would it be possible to do something like this?

const db = new Database(client);

await db.select().from(users);
//> return all users

await db.select().from(users).where("id = 1");
//> intercept from() method and return all users with a where condition

await db.select().from(users).where("id = 1").and("email like '%gmail%'");
//> intercept previous two methods and run query with additional and condition

await db.select().from(users).where("id = 1").and("email like '%gmail%'").and("type = 'END_USER'");
//> similar with infinite `and` chains

what i want is being able to chain methods but it also depends on what methods are chained and return the result according to that.

i've read about Proxy and Reflect but i couldn't make any sense from it, any help would be much appreciated!





Java ClassLoader: Get static field in a JAR 1 use by another JAR 2

I want to extract static field from another program. That program is launched through java reflection and URLClassLoader:

private static final String ProgramClassName = "com.myProject.MyMainClass"; 
private static final String ProgramLocation = "/home/user/program/22.3.0/launcher/target/program.jar";
private static final String[] ProgramArguments ={""}; 

<...>

URL[] urls = new URL[]{ new URL("jar:file:" + ProgramLocation +"!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls, getClass().getClassLoader());
Class<?> classToLoad = Class.forName (ProgramClassName , true, cl);
Method method = classToLoad.getDeclaredMethod ("main", String[].class);
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance, (Object)ProgramArguments);

Class com.myProject.MyMainClass uses a static field of another class AnotherMyClass placed in different JAR.

That JAR is loaded properly. I know it because program return correct result (that is based on AnotherMyClass). But when i try to access AnotherMyClass field i get exception:

Class<?> anotherClass = Class.forName (AnoterhClassName, true, cl);
java.lang.ClassNotFoundException: com.myProject.MyMainClass
    at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:445)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:587)
    at java.base/java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:872)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:467)

How could i load exactly that instance of class that was used by method.invoke (instance, (Object)ProgramArguments); call? Or maybe there is another way to launch another program and extract static field as result?





retrieve the instance of a class from the information contained in a MemberInfo in C#

Here is my case: I have a Class Main which has a field

Button button1 = new Button()

I have retrieved a MemberInfo from button1. I would now like to set its IsEnable property. After many fruitless searches I can't find the solution.

I want to do something like this Object obj = memberInfo.GetInstance();

I've tried this code:

Type type = currentForm.GetType(); // OK
FieldInfo field = type.GetField(member.Name); // OK


Control control = (Control)field.GetValue(member); // Not OK, control is Null
control.IsEnabled = false;

Thank you for your help!

A.





mercredi 5 juillet 2023

GraalVM and Kotlin inline value classes?

I would like to use value class in native image.

I marked it for reflection:

@Configuration(proxyBeanMethods = false)
@RegisterReflectionForBinding(MyValueClass::class, ...)
class BeanConfiguration {

However when running image I get:

org.graalvm.nativeimage.MissingReflectionRegistrationError: The program tried to reflectively invoke method public final java.util.UUID com.example.MyValueClass.unbox-impl() without it being registered for runtime reflection. Add it to the reflection metadata to solve this problem. See https://www.graalvm.org/latest/reference-manual/native-image/metadata/#reflection for help.
    at org.graalvm.nativeimage.builder/com.oracle.svm.core.reflect.MissingReflectionRegistrationUtils.forQueriedOnlyExecutable(MissingReflectionRegistrationUtils.java:97) ~[na:na]

How I can use inline value classes with GraalVM?





How I can use method call with some argument [Reflection]

I try to use Dynamic DLL (Hangfire Core). Some methods of this lib has non-standard arguments, for example


 public static IGlobalConfiguration UseSimpleAssemblyNameTypeSerializer([NotNull] this IGlobalConfiguration configuration)

If i want call method with reflection help, I did:

  1. Load Assembly
  2. Get type from assembly
  3. Get method from type
  4. Try Invoke method

and, I got error:

Object of type 'System.RuntimeType' cannot be converted to type 'Hangfire.IGlobalConfiguration'."

My code:

        private static void GetField(string typeName, string pathToDll, string fieldName)
        {
            Type GlobalConfigurationType = Assembly.LoadFile(@pathToDll).GetType(typeName);
            Type GlobalConfigurationExtensionType = Assembly.LoadFile(@pathToDll).GetType("Hangfire.GlobalConfigurationExtensions");

            var propertyInfos = GlobalConfigurationType.GetProperties();
            var someProperty = propertyInfos[0];

            var UseSimpleAssemblyNameTypeSerializerMethod = GlobalConfigurationExtensionType.GetMethod("UseSimpleAssemblyNameTypeSerializer");

            UseSimpleAssemblyNameTypeSerializerMethod?.Invoke(null, new object[] { someProperty.PropertyType });
        }

How to do the conversion correctly?

I tried to set .PropertyType as argument





How to get all properties of instance of EF entity that are used to build relation

I have to write generic repository, so also method to add entities. The problem is with entities that have relationships to existing entities - they must be tracked.

So I have to write some code that will recognize which properties of some entity are used to built relationship and attach them.

How? I thought about something like that:

public async Task StoreAsync(TEntity model, CancellationToken cancellationToken = default)
{
    foreach (var prop in model.GetType().GetProperties().Where(p => p.GetType().IsClass))
    {
        var related = prop.GetValue(model)!;
        if (_dbContext.Entry(related).State == EntityState.Detached)
            _dbContext.Attach(prop.GetValue(model));
    }

    await _dbContext.Set<TEntity>().AddAsync(model, cancellationToken);
    await _dbContext.SaveChangesAsync(cancellationToken);
}

But there are multiple problems with this code - firstly, we get properties that are not value types, so record, delegate and class. Delegates and records cannot be entities.

And another (im not sure if this is problem) thing is that we attach all detached entities. But what if some entity currently doesnt exist in database? What if we attach non-exsiting and will use it like existing?

So how to get all properties of instance of EF entity that are used to build relation?

I use NET7





mardi 4 juillet 2023

How to use Fluent Assertions Should().Throw() with NOT hardcoded exception type?

I would like to use fluent assertions .Should().Throw, but do not want to hardcode the type of the expected exception, instead I want it parametrized, so it is in a variable which type is Type.

Without parametrized it should be the following:

Action act = () => sut.MyMethod();
act.Should().Throw<MyException>().Where(myPredicate);

However I would like to the type of MyException to be a parameter in a variable





lundi 3 juillet 2023

How can I find the defined type of a property/field at runtime in TypeScript?

I am trying to get the type of a property/field in TypeScript. Specifically, from the property decorator. The property does not have a value set so I can not derive it from the type of the value. Consider an example

class Example {
  abc: ABC
}

How would I get the class/class name of the property? To be specific, not the JavaScript 'primitive' type given by typeof x but the actual class(name), in this case ABC.

I've tried using reflect-metadata but it doesn't look like it's retaining the defined type in the metadata, running the following code:

console.log(Reflect.getMetadataKeys(target) + ", " + Reflect.getMetadata("design:type", target, propertyKey)

// -> ", undefined"

So it doesn't seem like there is any metadata relating to the type defined, or at all for that matter.





How to get the name of the embedding struct in Go? [duplicate]

I have a struct Base which is embedded in another struct. I want to access the name of the embedding struct dynamically within a method of Base. Here's an example:

package main

type Base struct{
}

func (b *Base) GetStructName() {
    // want to access which embedding struct called it i.e Test
}

type Test struct {
    Base
}

func main() {
    test := &Test{}
    test.GetStructName()
}

I have tried utilizing the runtime and reflect packages, but unfortunately, they haven't provided the desired outcome.





dimanche 2 juillet 2023

Enumerate classes within packages and jars in Kotlin

I have a project in Kotlin with two modules (ProjectName.ModuleA and ProjectName.ModuleB). Within these modules I have a package (com.company.projectName.moduleA and com.company.projectName.moduleB). Module B references Module A.

In ModuleA I have a library that defines an interface (called Flag). This interfaces has implementations in ModuleA and ModuleB. I'm now writing tests for ModuleB.

The thing is that I'd like a function in ModuleA (the main library) that loads all the classes that implement the Flag interface. What I'm expecting is that, when I run the tests of ModuleA only the ModuleA implementations are loaded, but when I run the tests of ModuleB, both ModuleA and ModuleB implementations are loaded, because when I use this library in the "real world" I will like to load all the implementations that exist in the libraries referenced.

I have this code, but this code only loads the classes of the current package.

private fun findFlags(packageName: String) {
    // Translate the package name into an absolute path
    var name = packageName
    if (!name.startsWith("/")) {
        name = "/$name"
    }
    name = name.replace('.', '/')
    // Get a File object for the package
    val url: URL = SimplyTheFlag::class.java.getResource(name)
    val directory = File(url.file)

    if (directory.exists()) {
        // Get the list of the files contained in the package
        directory.walk()
            .filter { f -> f.isFile && !f.name.contains('$') && f.name.endsWith(".class") }
            .forEach { it ->
                val className = it.canonicalPath.removePrefix(directory.canonicalPath)
                    .dropLast(6) // remove .class
                    .drop(1) // drop initial .
                    .replace('/', '.')
                val fullyQualifiedClassName = "$packageName.$className"

                val isFlag = Class.forName(fullyQualifiedClassName).interfaces.any { i -> i.simpleName == Flag::class.java.simpleName }
                if (isFlag) {
                    availableFlags[className] = fullyQualifiedClassName
                }
            }
    }
}

How can I implement this?





Specifying child method with base class object in Java

I've written below snippet to produce better and reusable code in all of Child classes.

Base Entity :

public class BaseEntity{
     Integer id; 
     //setter getters etc
}

Child Entity :

public class MyChild extends BaseEntity{
    String name;
    //setter getters etc
}

I have many child classes that extends BaseEntity and want to write a method to remove boilerplate code.

Util Class :

public class Util{
    public String getName(BaseEntity base){
        return base != null ? base.getChild().getName() : "";
    } 
}

The problem is base.getChild.name() How to do something like that when child isn't in a composition form ? I've reading about Java Reflection but don't know how to do it in an optimise way in this scenario.. Is there any better option than Reflection ?