jeudi 31 août 2023

Swift 5 Comparing Object properties

I'm trying to compare two objects to check which properties were updated. I'm using Mirror to list the properties and try the comparison. Code is:

                let mirrorLote = Mirror(reflecting: l)
                let mirrorLoteUpd = Mirror(reflecting: lUpd)
                
                mirrorLote.children.forEach { child in
                    if (child.label != "id") {
                        mirrorLoteUpd.children.forEach { childUpd in
                            if (child.label == childUpd.label && child.value != childUpd.value){
                                addUpdatesDB(prop: child.label, val: childUpd.value)
                            }
                        }
                    }
                }

I'm getting the following error: "Type 'Any' cannot conform to 'RawRepresentable'" when trying to compare the values (child.value != childUpd.value).

Any ideas on how can I resolve this? Thanks!!





Why does the reflections library not work in a Spring Boot application?

I'm using org.reflections:reflections to find annotated classes on the classpath within a Spring Boot application. When running the app from the IDE, everything works fine. But when I build the FAT-JAR and run it directly, it can't find some classes. Here's a simplified version of my code:

// packagePrefixes is an array of strings
Reflections reflections = new Reflections(packagePrefixes, Scanners.TypesAnnotated);

for (Class<?> clazz : reflections.getTypesAnnotatedWith(Resource.BaseClass.class)) {
    // This works, it'll iterate through this
}

for (Class<?> clazz : reflections.getTypesAnnotatedWith(Listener.class)) {
    // This doesn't work, it won't iterate through this
}

Both annotations are annotated with

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)

I already tried using precise packages so that the library won't need to iterate recursively.

Does anyone know what the problem is here? Thanks for your help :)





lundi 28 août 2023

Why the result of descriptor.field_count() is different?

I'm using protobuf in Qt platform. function A and B are slot functions:

function A : void MainWindow::pushButton_load_clicked();
function B : void MainWindow::listWidget_LBM_itemClicked(QListWidgetItem *item);
dic : QHash<QString, const Message*> dic;

In function A, I store the pointer to Message to a hashtable.

for (auto message_ptr : res)
{
   // ...
   dic[funcid] = message_ptr;
}

In function B, I get the pointer to Message and use protobuf API to get the number of fields in the Message.

// ...
if(dic.find(funcid) == dic.end())
{
   qDebug() << "funcid " << funcid << " does not exist in dic" << endl;
   return;
}
const Message* message_ptr = dic[funcid];
const Descriptor* desc = message_ptr->GetDescriptor();
qDebug() << "funcid is : " << funcid << "desc->field_count() : " << desc->field_count() << endl;

But when I call function B for several times, the result of descriptor->field_count() is different. the output is:

funcid is :  "30001" desc->field_count() :  0 

funcid is :  "30007" desc->field_count() :  6881390 

the correct answer is 16 and 5.

I have tried to test whether the two pointers to Descriptor of one Message in function A and function B are the same. The answer is yes.

const Message* m1,m2,m3;
const Descriptor* d1,*d2,*d3;
int cnt = 0;
int f1, f2, f3;

function A:
dic[funcid] = message_ptr;
if(cnt == 0)
{
     m1 = message_ptr;
     d1 = m1->GetDescriptor();
     f1 = d1->field_count();
     ++cnt;
}
else if(cnt == 1)
{
     m2 = message_ptr;
     d2 = m2->GetDescriptor();
     f2 = d2->field_count();
     ++cnt;
}
else
{
     m3 = message_ptr;
     d3 = m3->GetDescriptor();
     f3 = d3->field_count();
}

function B:
const Message * message_ptr = dic[funcid];
if(funcid == "30007")
{
    auto d = message_ptr->GetDescriptor();
    if(message_ptr == m1)
        qDebug() << "equals m1" << endl;
    else
        qDebug() << "not equals m1" << endl;
    if(d == d1)
        qDebug() << "equals d1" << endl;
    else
        qDebug() << "not equals d1" << endl;
    if(d->field_count() == f1)
        qDebug() << "equals f1" << endl;
    else
        qDebug() << "not equals f1" << endl;
}
else if(funcid == "30001")
{
    auto d = message_ptr->GetDescriptor();
    if(message_ptr == m2)
        qDebug() << "equals m2" << endl;
    else
        qDebug() << "not equals m2" << endl;
    if(message_ptr->GetDescriptor() == d2)
        qDebug() << "equals d2" << endl;
    else
        qDebug() << "not equals d2" << endl;
    if(d->field_count() == f2)
        qDebug() << "equals f2" << endl;
    else
        qDebug() << "not equals f2" << endl;
}
else
{
    auto d = message_ptr->GetDescriptor();
    if(message_ptr == m3)
        qDebug() << "equals m3" << endl;
    else
        qDebug() << "not equals m3" << endl;
    if(message_ptr->GetDescriptor() == d3)
        qDebug() << "equals d3" << endl;
    else
        qDebug() << "not equals d3" << endl;
    if(d->field_count() == f3)
        qDebug() << "equals f3" << endl;
    else
        qDebug() << "not equals f3" << endl;
}

the output is :

equals m1 

equals d1 

not equals f1 

equals m2 

equals d2 

not equals f2 

equals m3 

equals d3 

equals f3 

Does anyone know the reason? Thanks in advance.

I'm expecting to get the correct result of descriptor->field_count() in function B.





Does PHP8 Reflection more bad performance versus PHP7 without reflection

I have re write my code from old php 7.4 scripts. And i see my code be more slower than old version My old models export data from method toArray And his representation was like that

public function toArray()
{
   return [
      "id" => $this->id;
      "name" => $this->name;
      //And many other values
   ]
}

But now, with PHP 8, i have use reflection object to serialize my object. That take something like :

class MyModel extends Model
{
   #[AttributeExport]
   private int $id;

   #[AttributeExport]
   private string $name;
}

//In Model

abstract Model implement JsonSerialize
{
   function jsonSerialize(): array
   {
      //Here i get all my attributes from current class
      //And i construct array to return
   }
}

I may be mistakenly thinking that the problem may come from there. But do you think that on a large volume of data, this strategy can have an impact?

I used more abstract class compared to the old version to avoid code duplication. Dont know if that can impact too





samedi 26 août 2023

Can I dynamically get an argument name of a method (not parameter name)?

Here's code

    public Configuration setProperty(int someSpecificProperty) {
        MyAppUtil.requirePositive(someSpecificProperty, "someSpecificProperty");
        this.someSpecificProperty = someSpecificProperty;
        return this;
    }
// MyAppUtil
    static void requirePositive(int property, String propertyName) {
        if (property <= 0) {
            throw new IllegalPropertyException(propertyName, PropertyIssue.NON_POSITIVE);
        }
    }
public class IllegalPropertyException extends RuntimeException {
    private static final String FORMAT = "%s value is invalid: should be %s";
    public IllegalPropertyException(String propertyName, PropertyIssue propertyIssue) {
        super(String.format(FORMAT, propertyName, propertyIssue.whatItShouldBeInstead()));
    }

    @RequiredArgsConstructor
    public enum PropertyIssue {
        NULL("not null"), EMPTY("not empty"), NON_POSITIVE("greater than zero");

        private final String whatItShouldBeInstead;

        String whatItShouldBeInstead() {
            return whatItShouldBeInstead;
        }
    }
}

Notice how I pass both a property and that property's name. I am wondering whether I could get that information about the argument name dynamically so that the client (or rather, I) don't have to pass it manually each time. It would've been nice if I could call the requrePositive() method like this (and MyAppUtil figured out the argument name itself):

    public Configuration setSpecificProperty(int someSpecificProperty) {
        MyAppUtil.requirePositive(someSpecificProperty);
        this.someSpecificProperty = someSpecificProperty;
        return this;
    }

Is there a way to do that?





How to pass a method name (safely) in Go

Is it possible to pass a method name in a safe manner? Currently I'm simply passing the method name as a string and match it using reflect but I wonder if it would be possible to pass it in a more safe manner(i.e as below) to prevent misspelling it or code getting out of sync (i.e. method name being renamed).

 package main

func Exists[T any](method any) string {
    // we extract the method name from the method/function itself. Impossible?

    // return the method name if it exists
    return ""
}

func main() {
    //we pass the method itself instead of its name (i.e. "Hello")
    m := Exists[X](X.Hello)
    if m != "Hello" {
        panic("expected  Hello")
    }
}

type X struct{}

func (X) Hello()   {}
func (X) GoodBye() {}

Play me





vendredi 25 août 2023

Get implementer class type

I have the below code

public abstract class abstract1
{
    public void Test1()
    {
        // Do something
    }
}

public class class1 : abstract1
{
}

public class Class1Test
{
    public void InvokeTest1()
    {
        Class1 c1 = new Class1();
        c1.Test1();
    }
}

How can I get that Test1 method invoked from Class1 then abstract1 for logging purposes?

Thanks,





Create a Dictionary using reflection from a property of a parent class using refleciton [duplicate]

I am trying to make a reference class creator. I it mostly working but dictionary I have run into some issues.

The problem is I have methods like:

static Dictionary<TKey, TVal> GetDictionary<TKey, TVal>(Type type1, Type type2)
{
    var v1 = GetGeneric<TKey>(type1);
    var v2 = GetGeneric<TVal>(type2);

    return new Dictionary<TKey, TVal> { { v1, v2 } };
}

static T GetGeneric<T>(Type t)
{
    if (t == typeof(string))
        return (T)(object)" ";

    if (t == typeof(int) || t == typeof(long) || t == typeof(float) || t == typeof(decimal))
        return (T)(object)0;

    return (T)(object)null;
}

This can be called on a PropertyInfo object info on a parent class like so:

if (p.PropertyType.Name == "Dictionary`2")
{
    var t1 = p.PropertyType.GenericTypeArguments[0];
    var t2 = p.PropertyType.GenericTypeArguments[1];
    var ty1 = t1.BaseType;

    
    //Kind of defeats the point here.  If I make args use TKey, TVal then it blows up on casting to TKey, TVal...
    var d = GetDictionary<string, string>(t1, t2);
    p.SetValue(obj, d);
}

However you can see I had to set the types as they cannot gather them except explicitly. I have messed with changing the types to use Activator as well as trying expressions and such.

Ultimate the goal is to make a tool that can just make base types with defaults for many differing classes. I don't have to use reflection I just thought it would be the easiest way to do this. I can use .NET 6 so if there are newer syntax to do this, that would be prefered. I saw a lot of older code doing this here.

The duplicate suggested from what I gather I appreciate but I am not certain that is what I want. In this example you would make method to make calls to generics. I want to be able to do:

Dictionary<string, int> Dictionary<int, string> Dictionary<string, string> Dictionary<int, DateTime>

From reflection and make defaults. I have done other pieces but I am not certain if this would do much beyond make me make more methods to do this. I currently am just returning an object currently with types as my interim solution and just adding each case as they come up. But I was curious if I could do this at runtime easier.

This:

Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = { p.PropertyType.GenericTypeArguments[0], p.PropertyType.GenericTypeArguments[1] };
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);
p.SetValue(obj, o);

Works for what I need. I just need to populate defaults.





Unhandled exceptions: java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException [duplicate]

public class Demo1 {
    //we will see how we can use Annotations in Java and create Are own     annotations
    public static void main(String[] args) {
        @SuppressWarnings("unchecked")

        Cat cat1 = new Cat("kasem");

//        System.out.println(cat.getClass().isAnnotationPresent(veryImportant.class));
                     for(Method  meethod : cat1.getClass().getDeclaredMethods() ){
                        if( meethod.isAnnotationPresent(Runimmedietly.class))
                        {
                            meethod.setAccessible(true); // Make the method accessible
                            meethod.invoke(cat1);// output should hello world

                        }

                     }

    }

hey guys im trying to invoke the method of the object cat1 but it's giving me this error java: unreported exception java.lang.IllegalAccessException; must be caught or declared to be thrown

package optionalsjJava;

import annotationsJava.*;

@veryImportant
public  class Cat {
//    @veryImportant //'@veryImportant' not applicable to field
        String name;
        int i;

    public Cat(String name) {
        this.name = name;


    }
    @Runimmedietly
    public static void number() {
        System.out.println("hello world");    }

i tried to make a try throw exeption, it did remove the error but its giving me a blank output





JobRunr: InstantiationException in ReflectionUtils.newInstance

I'm using JobRunr 6.3.0 for scheduling recurring background jobs in Java, and I encounter a problem with reflective access.

I'm trying to have an abstract class that implements the job scheduling logic, creating one job that calls an abstract method which is implemented in each child class. Like this:

public abstract class Blubb {

    public Blubb() {
        this(...defaultArgs);
    }

    protected Blubb(defaultArgs) {
        // set up
    }

    protected abstract String name();

    protected abstract Iterator<Object> getObjectsFromExternalSource();

    public void load() {
        JobScheduler scheduler = JobRunr
            .configure()
            .useStorageProvider(new InMemoryStorageProvider())
            .useBackgroundJobServer()
            .initialize()
            .getJobScheduler();

        scheduler.createRecurrently(
            RecurringJobBuilder
                .aRecurringJob()
                .withId(name())
                .withDuration(Duration.ofSeconds(10))
                .withDetails(this::run)
                .withAmountOfRetries(2)
        );
    }

    public void run() {
        Iterator<Object> objects = getObjectsFromExternalSource();

        while (objects.hasNext()) {
            // do stuff
        }
    }
}

Job creation works, and the job in the database looks fine:

{
  "_id": "name",
  "version": 0,
  "jobAsJson": "{\"version\":0,\"jobSignature\":\"org.example.blah.Blubb.run()\",\"jobName\":\"org.example.blah.Blubb.run()\",\"amountOfRetries\":2,\"labels\":[],\"jobDetails\":{\"className\":\"org.example.blah.Blubb\",\"staticFieldName\":null,\"methodName\":\"run\",\"jobParameters\":[],\"cacheable\":true},\"id\":\"name\",\"scheduleExpression\":\"PT10M\",\"zoneId\":\"Etc/UTC\",\"createdAt\":\"2023-08-25T06:39:29.844981739Z\"}",
  "createdAt": {
    "$numberLong": "1692945569844"
  }
}

But everytime it tries to run the job, I get the following exception:

WARN  o.j.server.BackgroundJobPerformer - Job(id=a444fd50-843a-4464-88a1-e51530056b3f, jobName='org.example.blah.Blubb.run()') processing failed: An exception occurred during the performance of the job
org.jobrunr.JobRunrException: JobRunr encountered a problematic exception. Please create a bug report (if possible, provide the code to reproduce this and the stacktrace)
    at org.jobrunr.JobRunrException.shouldNotHappenException(JobRunrException.java:43)
    at org.jobrunr.utils.reflection.ReflectionUtils.newInstance(ReflectionUtils.java:156)
    at org.jobrunr.server.runner.AbstractBackgroundJobRunner$BackgroundJobWorker.getJobToPerform(AbstractBackgroundJobRunner.java:46)
    at org.jobrunr.server.runner.AbstractBackgroundJobRunner$BackgroundJobWorker.run(AbstractBackgroundJobRunner.java:36)
    at org.jobrunr.server.runner.AbstractBackgroundJobRunner.run(AbstractBackgroundJobRunner.java:20)
    at org.jobrunr.server.BackgroundJobPerformer.runActualJob(BackgroundJobPerformer.java:89)
    at org.jobrunr.server.BackgroundJobPerformer.performJob(BackgroundJobPerformer.java:64)
    at org.jobrunr.server.BackgroundJobPerformer.run(BackgroundJobPerformer.java:42)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.InstantiationException: null
    at java.base/jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    at org.jobrunr.utils.reflection.ReflectionUtils.newInstance(ReflectionUtils.java:154)

Any idea what I'm doing wrong? Is this a problem with the class constructors? I have a public no-args constructor and an additional protected constructor in both the abstract class above and in the child classes. And I think it used to work before, when I only had one public default constructor.





jeudi 24 août 2023

reflection floor with blur without postprocessing

actually I want the reflection floor with realistic blurred reflection and I used reflector for that floor but its like a mirror enter image description here.

Is there any possibility to make blurred reflection of control the size of reflection with reflector





mercredi 23 août 2023

set and get entity value dynamically through a function

Im trying to make a function that parses a jwt token and sets them in a model with getter setters dynamically. Function is called at the very bottom.

@Autowired
private ObjectMapper objectMapper;

public Object decryptRequest(ClientRequest request, Class<?> clazzToMap) throws Exception {
    String jwt = request.getEncryptedPayload().split(" ")[1];
    log.info("Removed Bearer: {}", jwt);
    String body = jwt.split("\\.")[1];
    log.info("Extracted body: {}", body);
    byte[] content = Base64.getUrlDecoder().decode(body);
    Object reqConverted = objectMapper.readValue(content, clazzToMap);

    log.info("Reading fields from: {}", clazzToMap.getName());
    log.info("Field value: {}", clazzToMap.getDeclaredFields()[0]);

    // Object obj = PaymentRequest.class.getConstructor(PaymentRequest.class).newInstance(reqConverted);

    Field[] fields = reqConverted.getClass().getDeclaredFields();
    log.info("Field length: {}", fields.length);
    for(Field field : fields) {
        field.setAccessible(true);
        log.info("{} : {}", field.getName(), ???);
    }
    
    return reqConverted;
}

@Getter
@Setter
public class PaymentRequest {
   private String accountNo;
   private String accountName;
   private String item;
   private String price;
}

//Function is called like this
PaymentRequest request = (PaymentRequest) cryptService.decryptRequest(cReq, PaymentRequest.class);

What's the best way to do it? I'm not able to figure out what the '???' is in the code above.





Reflection in Flutter

I am trying to dynamically build a form according to specific class members and annotations. Because dart:mirrors is not available in Flutter SDK I am trying to access metadata with the reflectable package.

First I created classes for form declaration and annotation

class FormDeclaration {
  @DynamicFieldAttribute(label: 'Name and Surname', order: 1)
  String? name;
  @DynamicFieldAttribute(label: 'Age', order: 2)
  int? age;
  @DynamicFieldAttribute(label: 'Are you married?', order: 3)
  bool? isMarried;
}

class DynamicFieldAttribute {
  final String label;
  final int order;
  const DynamicFieldAttribute({
    required this.order,
    required this.label,
  });
}

I added reflectable package and created Reflector class.

class Reflector extends Reflectable {
  const Reflector() : super(metadataCapability, declarationsCapability, topLevelInvokeCapability, invokingCapability, typeRelationsCapability, typingCapability);
}

const reflector = Reflector();

I'm trying to access FormDeclaration members and their annotations. So I will build the form. Of course, this is only an example of the problem, so it was so simple with three basic and meaningless members.

initializeReflectable();
    ClassMirror classMirror = reflector.reflectType(FormDeclaration) as ClassMirror;
    classMirror.instanceMembers.forEach((key, value) {
      print(value.simpleName);
    });

The code above list the members of FormDecleration class. But I couldn't get the metadata of each member. It will be wonderful if I can query the members with their metadata parameter value (e.g order)

Here is the full source of example





mardi 22 août 2023

Call ImmutableArray

I am trying to call create an immutable array given an object variable that actually has a type of an T[] under the hood. How to do that using a Reflection. The problem is ImmutableArray.Create has many overloads and I get an ambigous method exception.

var method = typeof(ImmutableArray).GetMethod(nameof(ImmutableArray.Create)).Invoke(null, arr);




lundi 21 août 2023

Why do exceptions occur when using reflection in jdk17?

I need to obtain the value in the current ThreadLocal through reflection

but there is an exception about "*module java.base does not "opens java.lang" to unnamed module *"

And after adding the following configuration to the jvm startup parameters, the exception was resolved

--add-opens
java.base/java.lang=ALL-UNNAMED
--add-opens
java.base/java.lang.ref=ALL-UNNAMED

My questions :
1. Why the objects defined by myself, no error reported

  public class Record implements Serializable {
  private String name;
  // ....
  }

2. Is there any other way besides adding startup parameters in the jvm


java -version

java version "17.0.3" 2022-04-19 LTS
Java(TM) SE Runtime Environment (build 17.0.3+8-LTS-111)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.3+8-LTS-111, mixed mode, sharing)

My Code

public class TT {
    public static void main(String[] args) throws Exception {

        Thread thread = Thread.currentThread();
        Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        Object threadLocals = threadLocalsField.get(thread);
        System.out.println(threadLocals);
    }

}

the detail error

Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field java.lang.ThreadLocal$ThreadLocalMap java.lang.Thread.threadLocals accessible: module java.base does not "opens java.lang" to unnamed module @327471b5
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
    at com.moan.message.base.remote.service.helper.TT.main(TT.java:19)

One useful way: add vm option

--add-opens
java.base/java.lang=ALL-UNNAMED
--add-opens
java.base/java.lang.ref=ALL-UNNAMED




vendredi 18 août 2023

C# Static Constructor Call Hierarchy

I have a project with around 100k XML configuration files for managing test equipment. In order to make the files easier to update, I want to be able to port them around to Excel, Access, etc. I've written VBA code to do this, but it is painfully slow. C# is orders of magnitude faster and offers more utility. I created XML Schema to read the XML, but now I want to create a set of reusable data objects that manage the reading and writing to various formats and derived objects that specify the data content.

I decided to build a two-tier data structure, but the static constructors don't seem to perform as one would expect, and I need a workaround.

public abstract class Data_Structure {
    private static readonly Dictionary<string, int> _DatIndex = new Dictionary<string, int>();
    private static string _Name = "";
    private string[] _Data = null;
    protected static void Init(string datName, List<string> listProps) {
        int iIndex = 1;
        _Name = datName;
        foreach (string iProp in listProps) {
            _DatIndex.Add(iProp, iIndex);
            iIndex++;
        }
    }
    public Data_Structure() {
        _Data = new string[_DatIndex.Count + 1];
    }
    public static Dictionary<string, int> Get_PropList => _DatIndex;
    public static string Get_Name => _Name; 
    public string Prop_Get(string Prop_Name) {
        return this._Data[_DatIndex[Prop_Name]];
    }
    public void Prop_Set(string Prop_Name, string Prop_Value) {
        this._Data[_DatIndex[Prop_Name]] = Prop_Value);
    }
    // Code to manage input/output
}
public class Data_Item : Data_Structure {
    static Data_Item() {
        List<string> listProps = new List<string>();
        PropertyInfo[] arryProps = typeof(Data_Item).GetProperties();
        foreach (PropertyInfo iProp in arryProps) {
            listProps.Add(iProp.Name);
        }
        Init("Data_Item_Name", listProps);
    }
    public string Property1 {
        get => this.Prop_Get("Property1");
        set => this.Prop_Set("Property1", value);
    }
    // More Properties...
}

The idea is that Data_Structure can be the interface between all the different I/O formats. For each new XML file type, I will create a child instance (i.e. Data_Item) that defines its properties. I want to do it this way because I can use things like BindingList<T>, etc.

When I go to use the code, I try and pull the property list like so:

public void testFunction() {
    Console.WriteLine(Data_Item.Get_PropList.Count); //Outputs 0
    Data_Item tempItem = new Data_Item();
    Console.WriteLine(Data_Item.Get_PropList.Count); //Outputs correct number of properties
}

I'm not too familiar with reflection, but I understand its really slow during execution. In the above code, the intent is to front-load the reflection parts so at runtime (when iterating across 100k files) it executes faster. Also, any suggestions to make the derived classes simpler to define would be much appreciated. Thank you!

I am using C# 7.3 due to limitations on my computer. I am also not able to use Linq.





Unity3D Game ErrorLog

when i run my game app which made by Unity3D,it console show errorlog like this: Unity: MissingMethodException: System.Reflection.Emit.DynamicMethod::destroy_dynamic_method(System.Reflection.Emit.DynamicMethod) at System.Reflection.Emit.DynamicMethod.destroy_dynamic_method (System.Reflection.Emit.DynamicMethod m)[0x00000] in :0 at System.Reflection.Emit.DynamicMethod.Finalize ()[0x00000] in :0 System.UnhandledExceptionEventHandler:Invoke(Object, UnhandledExceptionEventArgs)

But my app running well, can guys help me!

it mean C# reflection error,but i am not sure





jeudi 17 août 2023

Get static field through reflection without triggering initialization?

We have a WAR application which uses a third-party library that creates a threadpool with a running thread as a static field of one of its internal classes. When we undeploy the WAR, this thread continues running. To work around this, I want to run some code during undeployment which uses reflection to access the private static field and shut down the thread pool.

The threadpool is created in a static initializer for the class. It's possible the class in question hasn't been loaded or initialized when our shutdown code runs, and I don't want the shutdown code to initialize the class just to shut it down again if I can avoid that.

I can use the three-argument form of Class.forName() to get the class without initializing it. However, after getting the Field that I want, getting the value of the field still triggers the class to be initialized. I'm looking for a way to avoid that.

Here is some example code:

package scratch;
public class A {
    private static final String field;
    static {
        System.out.println("A initializing");
        field = "I'm initialized!";
    }
}

package scratch;
public class B {
    public static void main(String[] args) {
        // var a = new A();
        try {
            System.out.println("B starting");
            var clazz = Class.forName("scratch.A", false, B.class.getClassLoader());
            System.out.println("B got class");
            var field = clazz.getDeclaredField("field");
            System.out.println("B got field");
            field.setAccessible(true);
            System.out.println("B set accessible");
            var value = field.get(null);
            System.out.println("B got value '" + value + "'");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Running this code produces this output:

B starting
B got class
B got field
B set accessible
A initializing
B got value 'I'm initialized!'

The call to Field.get() triggers initialization of the class.

I just want to avoid initializing the class (if it's not already initialized) in the process of accessing this field to shut it down. Is there any way to avoid fetching the class if it's not already loaded? Or to test whether it's initialized before fetching the field? Or to fetch the value of the field without triggering initialization?





mercredi 16 août 2023

How can I convert T into an instance of an object?

I am trying to keep this method as generic as possible. I am passing in a dynamic class. I want to create an instance of that class so that I can return it back to my controller. I am stuck on creating the instance. Here is what I have so far

This is how I call it from my controller

       public async Task<IActionResult> GetClassById(Guid id)
        {
            return Ok(await _contribRepo.Get<MyModelClass>(id));
        }

Here are the methods that take in a class type of T and send back the type T back to my controller

       public async Task<T> Get<T>(Guid id) where T : class
        {
            
            var component = CommonHelper.GetAssemblyNameContainingType(default(T)); 
            using (var connection = new SqlConnection(_connectionString))
            {
                await connection.OpenAsync();
                component = await connection.GetAsync<T>(id);
            }

            return component;
        }


public static object GetAssemblyNameContainingType<T>(T? typeName) where T : class
        {
           
            var type = Assembly.GetExecutingAssembly()
                    .GetTypes()
                    .FirstOrDefault(x => x.Name == typeName.ToString()); <----typeName is null
            var obj = Activator.CreateInstance(type);

            return obj;
        }




How do I get the element type of a collection passed in a method?

Suppose I have some method that accepts a List<?>

public void method(List<?> list) {
    // some logic
}

How can I get the element type in runtime? Is it possible?

I found these suggestions (here on SO):

  1. ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0] (doesn't work, List is an interface and doesn't have a superclass)
// ChatGPT's work

public class App {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        List<Integer> integerList = new ArrayList<>();

        Type stringType = getListElementType(stringList);
        Type integerType = getListElementType(integerList);

        System.out.println("String List Element Type: " + stringType.getTypeName());
        System.out.println("Integer List Element Type: " + integerType.getTypeName());
    }

    private static Type getListElementType(List<?> list) {
        Type genericType = list.getClass().getGenericSuperclass();

        if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            return parameterizedType.getActualTypeArguments()[0];
        }

        throw new IllegalArgumentException("Unable to determine list element type.");
    }
}

Console output:

String List Element Type: E
Integer List Element Type: E
  1. Storing a corresponding class as a field during creation of a generic class instance (doesn't work, List is read-only, and it can't have any instance fields anyway since it's an interface)
/*
 from jqno's answer to "How can I learn actual type argument of an generic class?"
 Henning in his answer to "Get generic type of class at runtime" suggested a similar trick
*/

class ParameterizedClass<T> {
    private Class<T> type;

    /** Factory method */
    public static <T> ParameterizedClass<T> of(Class<T> type) {
        return new ParameterizedClass<T>(type);
    }

    /** Private constructor; use the factory method instead */
    private ParameterizedClass(Class<T> type) {
        this.type = type;
    }

    // Do something useful with type
}
  1. The TypeTools library. I still need some supertype

The TypeResolver class provides some of the following methods:

Type reify(Type type, Class<S> context)

Returns a fully reified type using type variable information from the context.

Type reify(Type genericType)

Returns a fully reified genericType using information from the generic declaration.

Class<?>[] resolveRawArguments(Class<T> type, Class<S> subType)

Resolves the raw arguments for a type using type variable information from a subType.

Class<?> resolveRawArgument(Class<T> type, Class<S> subType)

Resolves the raw argument for a type using type variable information from a subType.

Type resolveGenericType(Class<?> type, Type subType)

Resolves the generic type using type variable information from a subType.

Class<?> resolveRawClass(Type genericType, Class<?> subType)

Resolves the raw class for a genericType using type variable information from a subType.





Should I rather implement this in an attribute or in the loader code?

I know I can do something like

[SomeAttribute(typeof(SomeClass)]
public class SomeClass {}

From what I know I cannot get the type the attribute is applied to in any other way.

In the end I want to localize a string that is a descriptor of that class. Now I can use a static label to get the localized string from a resource file. I would simply use the type's name for that.

so my Attribute would have some property

public string Name => Properties.SomeNames.ResourceManager.GetString(_type.ToString());

Is this something that should be done in the attribute or in my reflection code that loads the types from an assembly?

I mean it is meta data for the type, so attribute should be a good place but on the other hand if I have to provide the type to the attribute first I don't win much right?

Any technical detail I'm missing or is this just preference?





mardi 15 août 2023

Go field name or path of a struct field pointer?

I know it would not be very idiomatic but I would like to know if it is possible to get the field name of a pointer using reflection assuming it is known that the pointer references a struct field (maybe even having the struct value in question). For example

package main

import "fmt"

type Example struct {
    Foo int
    Bar string
}

func GetFieldName(originStruct any, fieldPtr any) string { ... }

func main() {
    v := Example{ 42, "baz" }
    f := &(v.Foo)

    fmt.Println(GetFieldName(v, f))
    // Prints "Foo"
}

A more advanced version of this would recursively get the path of the field even if along the way there are structs or slices and return a full path to the nested field pointer.

For example GetFieldPath(v, &(v.Foos[3].Bar)) -> []any{"Foos", 3, "Bar"} or something similar.

Why would I ever need this? — I am building a small experimental frontend framework all in golang and I need this to implement double binding in a clean way (without passing strings around)





lundi 14 août 2023

How can I detect with reflection in Scala if a contructor parameter is implicit?

Suppose I have a

class A(msg: String)(using ctx1: Int, ctx2: Long)

and I want to tell that it has 2 implicit parameters using reflection.

I tried something like

val m = runtimeMirror(getClass.getClassLoader)
println(m.classSymbol(getClass).primaryConstructor.info.paramLists)

but this recognizes only one parameter list.

Also tried isImplicit

println(m.classSymbol(getClass).primaryConstructor.info.paramLists.head.map(_.asTerm.isImplicit))

and it did not work, returned false for all.

I'm using Scala 3.3





Loading platform specific DLLs from "runtimes" folder in .NET 6

I have modular a windows app (exe). App has almost no references to nugets. In other project I have nugget reference to 'System.DirectoryServices'. App loads my other project (module) dynamically without reference to it (in csproj).

When I try to call something from 'System.DirectoryServices', I get 'PlatformNotSupportedException', because only placeholder DLL is loaded and platform specific DLL from runtimes folder is not loaded even if the files are there. When I add nuget reference to the app, everything works fine, but I don't want to lose modularity that way.

Can you guys please explain it to me, what is wrong? How can I tell the app to "look for" DLLs in runtimes folder even without nuget added to the app and without?





dimanche 13 août 2023

Get static List<> field by Reflection

I have the following class:

    static class Sclass
    {
        internal static BitmapImage Img1 { get; private set; }
        internal static BitmapImage Img2 { get; private set; }
        internal static List<string> Names = new();
        internal static Dictionary<string, List<Creature>> Dict = new();
    }

I am trying to get all the above fields using reflection like so:

    var properties = typeof(Sclass).GetProperties(BindingFlags.NonPublic | BindingFlags.Static);

However, that only returns a collection of Img1 and Img2. I tried some different combinations of BindingFlags but I haven't been successful in getting neither Names nor Dict.

I read every reflection question I could find here but nothing worked.

How do I get a PropertyInfo[] collection of all 4 fields of my class Sclass?





vendredi 11 août 2023

How to add another (object) delegate to existing using reflection?

I don't know how to cast d for using += operator for adding next method to d.

Is here simplest way for it ? As explained first delegate lives outside the class and must be changed via reflection (not expression, expression tree, emit or so).

using System;
using System.Reflection;

public class A
{
    public void fn()
    {
        Console.WriteLine ("a.fn() \n");
    }
    public void fn1()
    {
        Console.WriteLine ("a.fn1()");
    }
    void start()
    {
         var cb = new B();
         FieldInfo fi  = cb.GetType().GetField("mD");
         MethodInfo mfn  = this.GetType().GetMethod("fn");
         
         object d = System.Delegate.CreateDelegate( fi.FieldType, this, mfn);
//              d += System.Delegate.CreateDelegate( fi.FieldType, this, mfn1); 
// Line above give me an error CS0019: Operator '+=' cannot be applied to operands of type 'object' and 'Delegate'
// I think it due d is object not MD()


        fi.SetValue(cb, d);
        cb.tst();
    }
    
    public static void Main(string[] args)
    {
        var ca = new A();
        ca.start();
    }
}
public class B
{
    public delegate void    MD();
    public          MD mD ;
    public B()
    {
        mD = fn;
        tst();
    }
    public void tst()
    {
        mD();
    }
    void fn()
    {
         Console.WriteLine ("b.fn() \n");
    }
}

I have no idea how to fix it simplest way. Of course I read some articles but still no way have.

Now code works fine if I'm not using += and generates next output:

b.fn()

a.fn()





mercredi 9 août 2023

GetProperty() returns null

My Problem: I have 5 properties I need to set and the code for each is identical except for a couple parameters. So rather than writing repeating code for each, I wanted to try reflection to set the values for all the parameters.

The properties are in the same class this code is running in, for example:

public MyClass
{
    public string? L1Value { get; set; }
    public string? L2Value { get; set; }
    public string? L3Value { get; set; }
    public string? L4Value { get; set; }
    public string? L5Value { get; set; }

    public void MethodToGetProperty()
    {
        var result = GetType().GetPropterty(L1Value);
    }
}

**In my actual code, I have a FOR loop that will dynamically create the parameter string name. However, I have to get this GetProperties() to work.

GetProperty(L1Value) is returning null. I used GetType().GetProperties() and I see all the properties and L1Value has a value.

The questions in Stackoverflow I found all point to either 1) it was a field, not a property (no getter or setter) or 2) the access modifier was incorrect or missing. Neither of these apply here.

enter image description here

I appreciate any suggestions you have.





Dynamically loaded class missing members at runtime

I'm trying to load a class dynamically and iterate through the declared fields within it. I'm finding that occasionally, a field that I have recently added to the dynamically loaded class is missing.

The catch (and yes, I understand this is not really best practice) is that the dynamically loaded class is modified by the program just before it is loaded.

Specifically:

  1. A "template" (for lack of a better word) .csv file is read (this can be updated in between runs of the program)
  2. A POJO class is generated based on that template (this is the class we want to dynamically load, and should be re-written on each run to reflect changes in the template)
  3. A Class object is created based on the full qualified name of the class we just made
  4. We iterate through the declared fields within the class.

I've tried making the function that actually generates the POJO class return a value to ensure that everything is running in order (not that that would ever happen but at this point I'm deeply lost).

I've also tried deleting the POJO entirely between runs of the program, to no avail.

The only potential resolution that I've found is running the whole program twice in a row, which seems to somehow make the changes to the POJO class fully settle.

This seems to indicate that in some way, when I load the generated class based on the qualified name, the previous version of the class (prior to any edits to the template) is loaded. The real question is why? Is it possible to ensure that I am loading the absolute most recent version of a class?





mardi 8 août 2023

How to pass in "authority" field to gRPC stub?

I am trying to replicate a grpcurl request like the one below in Java code:
grpcurl .... -authority addr1 addr2:portnumber package.service/endpoint
How can I replicate a call like this using grpc stubs?

I created a channel to addr2 and created a stub like this, then I call the service I want to access:

ManagedChannel channel = ManagedChannelBuilder.forAddress("addr2", "portnumber")
        .useTransportSecurity()
        .build();

ServerReflectionGrpc.ServerReflectionStub reflectionStub = ServerReflectionGrpc
            .newStub(channel)
            .withCallCredentials(new MyCallCredentials())
...

reflectionStub.serverReflectionInfo(streamObserver)

However, this throws a grpc UNIMPLEMENTED error, I believe passing in the authority flag in this approach will solve the issue since it is currently not being directed to the right address. How can you do this? It seems like the CallOptions class has a "withAuthority" method, but I don't see a way to attach CallOptions directly to the stub itself.

I also am unable to create the channel directly to addr1; this brings about some different authentication issues. Any ideas are appreciated, thanks





Instantiate a Record in a generic method

I am using a Record as a DTO:

public record AccountTypeDTO(string Id, string Name):IEntityDTOBase;

IEntityDTOBase is used only to access both properties Id and Name.

At this step I'm creating an instance in a generic method like that with reflection:

    internal async IAsyncEnumerable<TEntityDTO> GetAsyncDTO<TEntityDTO>() where TEntityDTO:class,IEntityDTOBase 
    {
        yield return (TEntityDTO)Activator.CreateInstance(typeof(TEntityDTO),Guid.NewGuid().ToString(),"thirdItem" ) ;           
    }

It works but I don't like.

Now I'm trying to follow this track:

    internal async IAsyncEnumerable<TEntityDTO> GetAsyncDTO<TEntityDTO>() where TEntityDTO:class,IEntityDTOBase,new()
    {
        yield return new TEntityDTO() { Id = Guid.NewGuid().ToString(), Name = "thirdItem" };
        
    }
  1. new() is mandatory to be able to create the instance in the generic method.
  2. As I have the new() constraint, the caller of the method complaining must be a non-abstract type with a public parameterless constructor, blà, blà, blà
  3. He also complains about Id and Name in the construction about readonly property

I can implement setters on AccountTypeDTO and parameterless constructor to probably solve the issue but I'll loose the immuability and the benefit of a record, not an option.

Is there any other option to avoid reflection?





lundi 7 août 2023

Generate getter/setter name from variable Name in java

I am looking for a library which gives generated getter method name by looking up variable name, I can do it my own naively through get+change the first letter of variable name to upperCase and then append to it.





Invoke method on generic object without parameters with Java Reflection

I am working on a generic printer utility that prints whatever object might come along as long it presents an invokePrint() method. The context asks me for a PrintDialogEditor object I get through reflection in the following manner. I tried all sorts of paremeter for that invoke method along that troubleshooting offered through Oracle IllegalArgumentException from Method.invoke() but I can't get passed that last line. My question: Does the Reflection API foresee operations on generic objects at all?

PrintDialogEditor pde = null;
U editor = au.getEditor(entity);
if(hasInvokePrint(editor)) {
  Method m = editor.getClass().getMethod("invokePrint");
  pde = (PrintDialogEditor) m.invoke(editor); // this line fails

I have been debugging along the Oracle troubleshooting for using the Method.invoke() method.





How to get the reflection type if I know the type name? [duplicate]

The following defines the type "Symbol" and stores the type in "SymbolType".

import (
    "reflect"
)

type Symbol string

var SymbolType reflect.Type = reflect.TypeOf(Symbol(""))

Is it possible to do this without creating an instance of "Symbol"?





Extracting Delegates in generic methods

After some benchmarks I noticed most of my methods I created which use reflection are very, very slow, especially when used in iterations. I found a post from C# Corner, which shows how to create delegates for the reflection methods, because the validation and security operations are only done once when creating the delegate instead of each loop.

The C# Corner post show a code example very similar to this:

public class Item
{
  public int Value { get; set; }
}


List<Item> list = Enumerable.Repeat(new Item(), 10000000).ToList();

int i = 0;
foreach (var element in list)
{
  i = element.Value;
  element.Value = 3; 
}

and then explains that using reflection instead has the drawback of drastically affecting performance:

PropertyInfo propInfo = typeof(Item).GetProperty("Value");

foreach (var element in list)
{
  i = (int)propInfo.GetValue(element);
  propInfo.SetValue(element, 3);
}

performance however can be improved by creating delegates:

Action<Item, int> setter = (Action<Item, int>)Delegate.CreateDelegate(
    typeof(Action<Item, int>), null,
    typeof(Item).GetProperty("Value").GetSetMethod());

Func<Item, int> getter = (Func<Item, int>)Delegate.CreateDelegate(
    typeof(Func<Item, int>), null,
    typeof(Item).GetProperty("Value").GetGetMethod());

foreach (var element in list)
{
  i = (int)getter(element);
  setter(element, 3);
}

Now some of my methods have generic type parameters and I haven't found out how to create delegates with generic parameters yet to get a similar performance boost. Example: Let's say I have following extension method and I want to move the reflection calls to delegates, how would I do this?

public static void SetValues<T>(this List<T> list)
{
  var propInfos = typeof(T).GetProperties().AsSpan();

  for(int i = 0; i < list.Count; i++) 
  {
    var element = list[i];
    for (int j = 0; j < propInfos.Length; j++)
    {

      var propInfo = propInfos[j];
      if (propInfo.PropertyType == typeof(int) && (int)propInfo.GetValue(element) == default)
        propInfo.SetValue(element, i);
    }
  }
}

I've found various solutions, that use an ILGenerator to do this, as found in this MSDN Blog Post, but that has honestly been a little to abstract for my taste. I'd like to stay with C#, if possible.





dimanche 6 août 2023

Kotlin reify is not getting the actual instance type

I'm trying to implement a ValueObject base class using Kotlin and DDD. As any value object must consider all attributes in the equals method, I decided to implement a single method using reflection, so no subclass will need to implement it.

My ValueObject class is as follows:

abstract class ValueObject {
    override fun equals(other: Any?) = when {
        this === other -> true
        other !is ValueObject -> false
        else -> deepEquals(other)
    }

    inline fun <reified T : Any> deepEquals(other: T): Boolean {
        val fields = T::class.java.declaredFields

        println(T::class)

        for (field in fields) {
            field.isAccessible = true
            val thisValue = field.get(this)
            val otherValue = field.get(other)
            if (thisValue != otherValue && (thisValue == null || !thisValue.equals(otherValue))) {
                return false
            }
        }
        return true
    }

    override fun hashCode() = hashFromReflection()

    private fun hashFromReflection(): Int {
        val fields = this::class.java.declaredFields
        var result = 17

        for (field in fields) {
            field.isAccessible = true
            val value = field.get(this)
            result = 31 * result + (value?.hashCode() ?: 0)
        }

        return result
    }

    protected abstract fun validate() : Notification
}

I implemented the following code to test:

class PhoneNumber (val code: String, val number: String) : ValueObject() {
    override fun validate(): Notification {
        return Notification()
    }
}

fun main() {
    val phoneNumber = PhoneNumber("33", "w")
    val other = PhoneNumber("3", "w")
    println(phoneNumber == other)
    println(phoneNumber.deepEquals(other))
}

However, the result is weird. If I call deepEquals directly, it works fine. But if I use == operator, it considers T as ValueObject (not PhoneNumber), finds no declaredFields, and gives me a wrong result:

class br.all.domain.common.ValueObject
true
class br.all.domain.common.PhoneNumber
false

What I'm doing wrong?





vendredi 4 août 2023

Is it possible to search for the code using Java reflection

I have a Java code

import org.springframework.web.client.RestTemplate;


public class SomeClass {
   public void doRequest(){
      ...
      restTemplate.postForEntity(someurl, body, String.class);
      ...
   }
}

is there a way I can find out the usage of restTemplate.postForEntity method in the jar file using java reflection? if so is there a way to find out the line in the file that method is used?





Public constructor isn't accesible

I have a class with 4 public constructors, but when I try to de-serialize it, it gives me this error:

java.io.InvalidClassException: jzez.Img; no valid constructor

The code of the class:

public class Img extends BufferedImage implements Serializable {

    
    public Img() {
        this(20, 20, 6);
    }
    private static final long serialVersionUID = 1L;

    public Img(int width, int height, int imageType) {
        super(width, height, imageType);
    }

    public Img(int width, int height, int imageType, IndexColorModel cm) {
        super(width, height, imageType, cm);
    }

    public Img(ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, Hashtable<?, ?> properties) {
        super(cm, raster, isRasterPremultiplied, properties);
    }

    public static Img getImg(BufferedImage bi) {
        ColorModel cm = bi.getColorModel();
        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = bi.copyData(null);
        return new Img(cm, raster, isAlphaPremultiplied, null);
    }

}

I made a class that takes a lot of BufferedImages and serializes them. But de-serializing gives an error. I expected it to de-serialize correctly and the constructors to be accesible





How to access and process Fields of Type Map in a Class using Java Reflection

I am trying to access and print all Fields of below mentioned Class (MainClass) using Java Reflection

public class MainClass{
  private int aInt;
  private char aChar;
  private boolean aBoolean;
  private Map<Integer, SubClass> subClassMap;

/*** Setters & Getters ***/

}

public class SubClass{
  private long aLong;
  private float aFloat;
  private double aDouble;

/*** Setters & Getters ***/
}

It is able to access all Fields and print the details like Type, Name etc using

(new MainClass()).getClass().getDeclaredFields()

But how I can access and print the details like Key and Value part of Field subClassMap of Type Map (Map<Integer, SubClass>).





mercredi 2 août 2023

Text existence of covariant property without generating AmbiguousMatchException

My base view model uses Type.GetProperty to verify that a given property (for which we are about to raise PropertyChanged) actually exists in the class.

It works great. But if you test for the existence of a property that you have overridden with a more derived type (ie.a covariant return types), an AmbiguousMatchException is generated. I can catch and avoid this but I would like to silence it. It makes my debugging experience more noisy.

Is there an alternate or more-specific way to test for the existence of such a property and NOT get an AmbiguousMatchException?

Here is an oversimplified version of the base view model.

public abstract class Observable  : INotifyPropertyChanged
{
    protected void RaisePropertyChanged(string propertyName)
    {
        try
        {
            if (null == type.GetProperty(propertyName)
                 Debug.Fail($"{propertyName} is not a public property of {type.FullName}");
            else
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        catch(AmbiguousMatchException)
        {
        }
    }
}

And here are some classes (deliberately stripped-down) that use covariant return types to on a property.

When I check for the existence of the "Geometry" property in the base class, I get the exception

public abstract class Shape  : Observable { public abstract Geometry        Geometry { get; } }
public          class Circle : Shape      { public          EllipseGeometry Geometry { get; } }
public          class Line   : Shape      { public          LineGeometry    Geometry { get; } } 




mardi 1 août 2023

How To Convert Object to T

I Have a operator class that a func is on it, if argument of Function(it is a Func) was int or float or string i can convert object and call Func with "Function((T)a)", when T be a List how can i convert object a to T? (i know that T is List of Something)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace GameToolkit.Operator
{
    public abstract class IOperator
    {
        public abstract Type OutputType { get; }
        public abstract Type[] GetInputTypes();
        public abstract object GetValue(object a);
        public ValueToken GetValues(object a)
        {
            var v = GetValue(a);
            return new ValueToken() { Type = v.GetType(), Value = v };
        }
    }
    public class SingleOperand<T, O> : IOperator
    {
        public Func<T, O> Function { get; set; }
        public SingleOperand()
        {
        }
        public SingleOperand(Func<T, O> function)
        {
            Function = function;
        }
        public override object GetValue(object a)
        {
            if (Function == null)
                return default(T);
            if (a.GetType().IsGenericType)
            {
                ///SOME CODE HERE!!!
            }
            else
            return Function((T)a);
        }
        public override Type OutputType => typeof(O);

        public override Type[] GetInputTypes()
        {
            return new[] { typeof(T) };
        }
    }
}