samedi 30 avril 2022

Reflection: how to assign an Array to Object's field

I use readValue of Jackson framework which returns Object[] (valueField). And I have an object bean with the field List<T> repository (targetField). I need to assign Array to that List, but the best I reached is that targetField holds 1 element which is the whole Array itself (look at attached image).

I tried to cast Object[] to List but I got ImmutableCollectionList instead of common array and targetField is just assigned the reference instead of value. New ArrayList() does not help. I tryed field.set(bean, valueField) with no result and ran into Array.newInstance(), but did not managed to implement it correctly in that case. I'm puzzled

private void installFieldConfig(Object bean, Field field) {
    ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class);
    File file = configProperty.configFileNameEnum().getConfigFile();

    Object targetField;
    Object valueField;
    if (AbstractDao.class.isAssignableFrom(bean.getClass())) {
        Class<?> singleClazz = ((AbstractDao<?>) bean).getTypeParameterClass();
        Class<?> arrayClazz = Array.newInstance(singleClazz, 0).getClass();
        try {
            targetField = field.get(bean); //successfully get the bean's field in which I want inject new value (ArrayList<T>)
            valueField = objectMapper.readValue(file, arrayClazz); //this is Jackson method, returns T[] 
            targetField = List.of(valueField); //here is the trouble
            field.set(bean, valueField); //also trouble
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Debug overview image





vendredi 29 avril 2022

DbSet variable table name

I am writting an application where I need to abstract the DbSet table name. Instead of calling _db.Activities.ToList() (where Activity is a table in Sql) the code below will work for any variable table input.

Now I wanted to use .Where(),.OrderBy(),.FromSqlRaw() and other methods on top of the existing code.

How can I write _db.Activities.FromSqlRaw(...) for example, with a variable table name, just like it is doing for the GetAll method.

This is my DbSet for Activity

public virtual DbSet<Activity> Activities { get; set; } = null!;

This is the method to get all records from a variable table

public dynamic GetAll(string Table)
        {
            var curEntityPI = _db.GetType().GetProperty(Table);
            var curEntityType = curEntityPI.PropertyType.GetGenericArguments().First();
            // Getting Set<T> method
            var method = _db.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
            // Making Set<SomeRealCrmObject>() method
            var genericMethod = method.MakeGenericMethod(curEntityType);
            // invoking Setmethod into invokeSet 
            dynamic invokeSet = genericMethod.Invoke(_db, null);
            // invoking ToList method from Set<> invokeSet 
            return Enumerable.ToList(invokeSet); 
        }

The general ideia comes from this post

https://ift.tt/if9Z0A5





Extract tags from Go struct as a reflect.Value

I'm trying to extract tags from a certain Value which is a struct. I am able to get the fields of the struct but unable to extract the tags. What am I doing wrong here? I've tried many different ways (using reflect.Type, interface{} etc) but all failed.


type House struct {
    Room string
    Humans Human
}

type Human struct {
    Name         string `anonymize:"true"` // Unable to get this tag
    Body         string
    Tail         string `anonymize:"true"` // Unable to get this tag
}

func printStructTags(f reflect.Value) { // f is of struct type `human`
    for i := 0; i < f.NumField(); i++ {
        fmt.Printf("Tags are %s\n", reflect.TypeOf(f).Field(i).Tag) // TAGS AREN'T PRINTED
    }
}

The reason I use reflect.Value as the parameter is because this function is called from another function in the following manner

    var payload interface{}
    payload = &House{}
    // Setup complete
    v := reflect.ValueOf(payload).Elem()
    for j := 0; j < v.NumField(); j++ { // Go through all fields of payload
        f := v.Field(j)
        if f.Kind().String() == "struct" { 
            printStructTags(f)
        }
    }

Any insights would be extremely valuable





Calling Java from Node.js

I'm trying to follow this simple tutorial about calling Java from Node.js:

My test script:

var java = require('java');
var javaLangSystem = java.import('java.lang.System');

javaLangSystem.out.printlnSync('Hello Java!');

Here is the console:

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
...
$ npm install java

added 18 packages, and audited 19 packages in 11s

1 package is looking for funding
  run `npm fund` for details

2 high severity vulnerabilities

To address all issues, run:
  npm audit fix

Run `npm audit` for details.
$ node test.js 
/home/Projects/test-java/node_modules/java/lib/nodeJavaBridge.js:240
  var fields = SyncCall(clazz, 'getDeclaredFields')();
                                                   ^

Error: Error running instance method
java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:208)
    at java.base/java.lang.invoke.MethodHandleImpl$1.reflectiveInvoker(MethodHandleImpl.java:1660)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:131)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)

    at Java.java.import (/home/Projects/test-java/node_modules/java/lib/nodeJavaBridge.js:240:52)
    at Object.<anonymous> (/home/Projects/test-java/test.js:2:33)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  cause: nodeJava_java_lang_NullPointerException {}
}
$ java --version
java 18.0.1 2022-04-19
Java(TM) SE Runtime Environment (build 18.0.1+10-24)
Java HotSpot(TM) 64-Bit Server VM (build 18.0.1+10-24, mixed mode, sharing)

What may be going wrong here?

I've tried to debug it and it seems that obj[syncMethodName].bind(obj) throws a java.lang.NullPointerException at java.base/java.lang.reflect.Method.invoke(Method.java:577) when

obj == class java.lang.System
syncMethodName == 'getDeclaredFieldsSync'




jeudi 28 avril 2022

C# InvokeMember - MissingMethodException: 'Method not found'

In a .NET Core 6 RestAPI application, I'm tracking global stock exchanges and have an instance of the below Exchange class called "ex".

public class Exchange
{
    public string CountryCode { get; set; }
    public string Currency { get; set; }
    public string DataSourceCode { get; set; }
    public int DaysHoursId { get; set; }
    public string ExchangeCode { get; set; }
    public string ExchangeName { get; set; }
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public DateTimeOffset LastUpdatedDate { get; set; }
    public string LastUpdatedStatus { get; set; }
    public DateTimeOffset NextUpdateDateTime { get; set; }
    public string Region { get; set; }
    public string Timezone { get; set; }
    public string Type { get; set; }
    public string Url { get; set; }
    public string Website { get; set; }
}

All fields are populated with non-null data. In this case, the body of my Postman call is: { "CountryCode": "USA", "Currency": "USD", "DataSourceCode": "IA2", "DaysHoursId": 2, "ExchangeCode": "AMEX", "ExchangeName": "AMEX",
"IsActive": true, "LastUpdatedDate": "2022-04-24T15:42:28.2533333+00:00", "LastUpdatedStatus": "OK", "NextUpdateDateTime": "2022-04-24T15:42:28.2533333+00:00", "Region": "NORTH AMERICA", "Timezone": "EST", "Type": "STOCK", "Url": "https://ift.tt/IzBjKyl", "Website": "www.AMEX.com" }

Using Reflection, I create a DataTable from this object with all columns except for "Id", which is an Identity primary key in the table to which data will be loaded, as follows:

 PropertyDescriptorCollection props = TypeDescriptor.GetProperties(ex);
 DataTable dt = new DataTable();
 foreach (PropertyDescriptor p in props)
 {
      if (p.Name != "Id")  // insert into an identity column not allowed.
      { 
           dt.Columns.Add(p.Name, p.PropertyType);
      }
 }

I then attempt to create a row in the dt datatable, as follows:

DataRow dr = dt.NewRow();
Type t = ex.GetType();
for (int i = 0; i <= dt.Columns.Count; i++)
{
    t.InvokeMember(dt.Columns[i].ColumnName, System.Reflection.BindingFlags.SetProperty, null, ex, new object[] { dt.Columns[i].ColumnName });
}

... which, when executed and traced, InvokeMember successfully iterated through the CountryCode, Currency, and DataSourceCode columns, but then - when it reaches DaysHoursId - threw a "System.MissingMethodException: 'Method MarketApi.Core.Entitites.Exchange.DaysHoursId' not found' exception.

Any insight as to what I'm doing wrong would be very much appreciated!





mercredi 27 avril 2022

Creating Actions via reflection with type parameters to proxy call

Given a simple object

public class Foo {
   public void RunAction(Action<int, string, byte> action) {
        Action(0, null, 0);
   }
}

And given a sample pseudo-code method that reads this class to obtain the action type via reflection:

public void DoProxy(object [] calledWithParameters) {
     ... some code ...
}

public void DoReflection(Foo foo) {
   var actionParameterInfo = foo.getType().getMethod("RunAction").GetParameters()[0];
   var parameterTypes = actionParameterInfo.ParameterType.GenericTypeArguments;
   // Now I have the action type and the Type[] of the necessary parameters.
}

In this case how could I create dynamically an Action that calls my DoProxy with the received parameters on call ?





SDN RYU Controller-Read DNS Header Flags in DNS Amplification Reflection Attack

I implement an SDN network with an RYU controller. I simulate a DNS amplification reflection attack.

Now I need to recognize legitimate from illegitimate DNS responses by reading some flags in the DNS header.

Does anybody have an idea how it is possible to read DNS flags in the RYU controller?

Thank you





Overwrite reference type without breaking references

I'm trying to write a system for loading a bunch of variables from disk at runtime. For a Unity game.

I have a wrapper class that allows floats, ints etc to be passed as references:

public class RefProperty<T>
{
    private T val;
    public T Val
    {
        get => val;
        set => val = value;
    }
    
    public RefProperty()
    {
    }
    public RefProperty(T value)
    {
        Val = value;
    }
}

I want to overwrite val with one loaded from disk without breaking references. In the following, target = source will update the value of target, but reference will no longer update when target is modified.

public class Program
{
    private RefProperty<float> source = new RefProperty<float>();
    private RefProperty<float> target = new RefProperty<float>();
    private RefProperty<float> reference = new RefProperty<float>();

    public void Run()
    {
        target.Val = 1;
        reference = target;
        Debug.Log(reference.Val); // returns 1
        
        source.Val = 5;
        target = source;
        Debug.Log(reference.Val); // returns 1
        
        ///////////////////////////////
        
        target.Val = 1;
        reference = target;
        Debug.Log(reference.Val); // returns 1
        
        source.Val = 5;
        target.Val = source.Val;
        Debug.Log(reference.Val); // returns 5
    }
}

The 2nd approach target.Val = source.Val does work. However, I am trying to avoid that because ultimately I want to iterate through the fields of a class holding loads of these with different types, and some child classes, and replace all the values without having to know the types:

public class RefPropertyChild : RefProperty<float>
{
    // float specific features
    public RefPropertyChild(float value)
    {
        Val = value;
    }
}


public class Parameters
{
    public RefProperty<bool> p1 = new RefProperty<bool>(true);
    public RefProperty<int> p2 = new RefProperty<int>(5);
    public RefPropertyChild p3 = new RefPropertyChild(6);
}


public class LoadData
{
    private Parameters sourceParams;
    private Parameters targetParams;

    void load()
    {
        foreach (FieldInfo field in typeof(Parameters).GetFields())
        {
            field.SetValue(targetParams, field.GetValue(sourceParams));
        }
    }
}

As before, this does modify the values, but breaks the references, I am assuming because it's pointing to a different memory location now? Is there any way to do this or do I have to explicitly handle each type and use the getter / setters?





lundi 25 avril 2022

Implementing Pseudo Enum Inheritance in Java using a Marker Interface

I'm using a Marker Interface to implement pseudo enum inheritance.

Let's say I define Marker class as follows:

public interface FieldInterface

Now I have have 5 enum classes that implement this interface.

enum Field1 implements FieldInterface
enum Field2 implements FieldInterface
enum Field3 implements FieldInterface
enum Field4 implements FieldInterface
enum Field5 implements FieldInterface

Each of the 5 enum "Field" class above defines a list of enums related to that field type. For example, enum Field1 might define enums: Field1A, Field1B, Field1C. Enum Field2 might define enums: Field2A, Field2B, Field2C

Now I need to convert plain text representation of each enum to the corresponding enum (similar to calling enum.valueOf(String)) without knowing which of the 5 enum classes the String belongs to.

One way to achieve this might be through reflection by first retrieving a list of all classes that implement said interface and iterating through all of the 5 enum classes until a match is found. However, I prefer to avoid reflection if possible (mainly due to performance reasons).

What other options are there to solve this problem?

Thanks





Using reflection on ProcessStartInfo to call it in a dynamic way

I have the following code in a jsp, which calls in a dynamic way a method:

            ....
            List<String> tsil = new ArrayList<String>();
            .....
            Class kj = Class.forName("test");
            Process w = (Process) kj.getMethod("method1").invoke(kj.getDeclaredConstructors()[0].newInstance(tsil));
            ....

I would like to do the same thing but in C# for an aspx page:

    .....
    ProcessStartInfo THf = new ProcessStartInfo();
    THf.FileName = "filename";
    THf.Arguments = "param1 "+arg;
    THf.RedirectStandardOutput = true;
    THf.RedirectStandardError = true;

    THf.UseShellExecute = false;
    Process Y = Process.Start(THf);
    ....

How can I do it, if is it possible?

If it is not possible, is there something similar to it?





C# Generic method for getting field names based on attributes

I am trying to make a generic method to be used in a lot of places in my code I can make it work with the following code:

public static void GetFieldNames(System.Object obj, List<string> list)
{
    // Getting the class
    Type t = obj.GetType();
    // Getting all the fields(Variables)
    FieldInfo[] fis = t.GetFields(BindingFlags.ExactBinding | BindingFlags.Instance | BindingFlags.Public);
    for (int i = 0; i < fis.Length; i++) 
    {
        // Filtering through the list and if the field(Variable) is marked with a ShowInToolTip attribute ....
        ShowInToolTip attribute = Attribute.GetCustomAttribute(fis[i], typeof(ShowInToolTip)) as ShowInToolTip;
        if (attribute != null)
        {
            list.Add(fis[i].Name);
        }
    }
}

But I have to specify which attribute I want the list to add in the method, meaning I have to create a new method every time I want to find different attribute to add.

So I am trying to have the attribute added to the method as a generic Type parameter I have the code below:

public static void GetFieldNames<Att>(System.Object obj, List<string> list) where Att : System.Attribute
{
    // Getting the class
    Type t = obj.GetType();
    // Getting all the fields(Variables)
    FieldInfo[] fis = t.GetFields(BindingFlags.ExactBinding | BindingFlags.Instance | BindingFlags.Public);
    for (int i = 0; i < fis.Length; i++) 
    {
        // Filtering through the list and if the field(Variable) is marked with a ShowInToolTip attribute ....
        Att attribute = Attribute.GetCustomAttribute(fis[i], typeof(Att)) as Att;
        if (attribute != null)
        {
            list.Add(fis[i].Name);
        }
    }
}

and I am implementing as follows:

List<string> stats = new List<string>();
CharacterStats characterStats;
GetFieldNames<Stat>(characterStats, stats);

But unfortunately I am getting a null reference error. It is quite late while typing this so I am sure I am making a simple error but if anyone could help just look over the code that would be much appreciated.





How to use reflection of Protobuf to modify a Map

I'm working with Protobuf3 in my C++14 project. There have been some functions, which returns the google::protobuf::Message*s as a rpc request, what I need to do is to set their fields. So I need to use the reflection of Protobuf3.

Here is a proto file:

syntax="proto3";
package srv.user;

option cc_generic_services = true;
message BatchGetUserInfosRequest {
    uint64 my_uid = 1;
    repeated uint64 peer_uids = 2;
    map<string, string> infos = 3;
}

message BatchGetUserInfosResponse {
    uint64 my_uid = 1;
    string info = 2;
}

Service UserSrv {
    rpc BatchGetUserInfos(BatchGetUserInfosRequest) returns (BatchGetUserInfosResponse);
};

Now I called a function, which returns a google::protobuf::Message*, pointing an object BatchGetUserInfosRequest and I try to set its fields.

// msg is a Message*, pointing to an object of BatchGetUserInfosRequest
auto descriptor = msg->GetDescriptor();
auto reflection = msg->GetReflection();
auto field = descriptor->FindFieldByName("my_uid");
reflection->SetUInt64(msg, field, 1234);
auto field2 = descriptor->FindFieldByName("peer_uids");
reflection->GetMutableRepeatedFieldRef<uint64_t>(msg, field2).CopyFrom(peerUids); // peerUids is a std::vector<uint64_t>

As you see, I can set my_uid and peer_uids as above, but for the field infos, which is a google::protobuf::Map, I don't know how to set it with the reflection mechanism.





dimanche 24 avril 2022

Check if entity has dependencies in Code First

I'm trying to check if my entity has any dependencies before allowing deletion:

Normally we can do this for each entity type by doing this:

public class Company{
   public int id;
   public string name;
   public virtual IList<Department> Departments { get; set; }
   public virtual IList<Building> Buildings {get;set;}
 
   public bool hasDependencies => Departments.Any() || Buildings.Any();
}

But I want to do this generically for any nagivational properties an entity could have

Note: Lazy loading is enabled.

public bool HasDependencies()
{
   int ExampleEntityId = 2; // just example
   Company companyEntity = _unitofwork.CompanyRepository.GetEntityById(ExampleEntityId);

   IEnumerable<PropertyInfo> propertyInfoList = _unitofwork.CompanyRepository.GetNavigationProperties();

   bool dependenciesExist = false;
   foreach (PropertyInfo property in propertyInfoList)
       {
            dependenciesExist = companyEntity.**property**.Any(); //This obviously doesn't work, but just to convey the intent.
            if (dependenciesExist) {
                    break;
            };
        }
            return dependenciesExist;
}

This is the GetNavigationProperties method:

        public IEnumerable<PropertyInfo> GetNavigationProperties() 
        {
            var modelData = _context.Model.GetEntityTypes(typeof(TEntity)).ToList()[0];
            var propertyInfoData = modelData.GetNavigations().Select(x => x.PropertyInfo);

            return propertyInfoData;
        }

I've looked in many pages including the following to figure this out:

EF5 How to get list of navigation properties for a domain object

Check if entity has references in other entities in Code First





How to use reflection to do the assignment for all kinds of fields

I'm working with Protobuf3 in a C++14 project.

Let's say that I have such a proto file:

syntax="proto3";
package srv.user;

option cc_generic_services = true;

message TestReq {
    uint32 seqid = 1;
    repeated uint64 userids = 2;
    map<string, string> infos = 3; 
};

message TestRes {
    uint32 resCode = 1;
};

service UserService {
    rpc RpcTest(TestReq) returns (TestRes);
};

Now, in my C++ project, I do

void func(const std::vector<uint64_t>& vec, const std::map<std::string, std::string>& mp) {
    srv::user::TestReq req;
    // use reflection to set each field of req
    const google::protobuf::Reflection* ref = req.GetReflection();
    const google::protobuf::Descriptor* des = req.GetDescriptor();
    initReq(ref, des, vec, mp, "seqid", "userids", "infos");
    ...
    ...
}

void initReq(const google::protobuf::Reflection* ref, const google::protobuf::Descriptor* des, const std::vector<uint64_t>& vec, const std::map<std::string, std::string>& mp, const std::string& fieldName1, const std::string& fieldName2, const std::string& fieldName3) {
    const google::protobuf::FieldDescriptor* fdes = nullptr;
    fdes = des->FindFieldByName("fieldName1");
    google::protobuf::Message* msg1 = ref->MutableMessage(req, fdes);
    *msg1 = 12345; // ERROR!
    fdes = des->FindFieldByName("fieldName2");
    google::protobuf::Message* msg2 = ref->MutableMessage(req, fdes);
    *msg2 = {vec.begin(), vec.end()}; // ERROR!
    fdes = des->FindFieldByName("fieldName3");
    google::protobuf::Message* msg3 = ref->MutableMessage(req, fdes);
    *msg3 = {mp.begin(), mp.end()}; // ERROR!
}

This won't work. Because msg1, msg2 and msg3 are all Message*. Meaning that I lost their real types in the function initReq.

Can we get the real type of google::protobuf::Message in the function initReq?





samedi 23 avril 2022

Python reflection after module reloading

I am trying to reflect a module after reloading it. Every time I change the module, I need to reflect it to see its current state. The problem is that it remembers all of its previous states. Here is my code.

main.py

from tkinter import *
from importlib import reload

def fun():
    import second
    reload(second)
    print(dir(second))

root=Tk()
Button(root,text='reload',command=fun).pack()
root.mainloop()

second.py

var1='hello'

When I change the variable name in 'second.py' from 'var1' to 'var2' for example, it prints both variables 'var1' and 'var2'. I need only the latest version of the module (only 'var2').

Thanks for help





vendredi 22 avril 2022

javassist - How can I replace a method body without extra startup flags on Java 17?

I'm trying to redefine a method at runtime using javassist, but I'm running into some issues on the last step, because of the weird requirements I have for this:

  • I can't require the user to add startup flags
  • My code will necessarily run after the class has already been defined/loaded

My code looks like this:

        val cp = ClassPool.getDefault()
        val clazz = cp.get("net.minecraft.world.item.ItemStack")
        val method = clazz.getDeclaredMethod(
            "a",
            arrayOf(cp.get("net.minecraft.world.level.block.state.IBlockData"))
        )

        method.setBody(
            """
            {
            double destroySpeed = this.c().a(this, $1);
            
            if (this.s()) {
                return destroySpeed * this.t().k("DestroySpeedMultiplier");
            } else {
                return destroySpeed;
            }
            }
            """.trimIndent()
        )
        
        clazz.toClass(Items::class.java)

(I'm dealing with obfuscated method references, hence the weird names)

However, calling .toClass() causes an error as there are then two duplicate classes on the class loader - and to my knowledge there's no way to unload a single class.

My next port of call to update the class was to use the attach API and an agent, but that requires a startup flag to be added (on Java 9+, I'm running J17), which I can't do given my requirements. I have the same problem trying to load an agent on startup.

I have tried patching the server's jar file itself by using .toBytecode(), but I didn't manage to write the new class file to the jar - this method sounds promising, so it's absolutely on the table to restart the server after patching the jar.

Is there any way I can get this to work with my requirements? Or is there any alternative I can use to change a method's behavior?





mercredi 20 avril 2022

C# Reflection get the instance behind FieldInfo

I am having an issue with Reflection, which I can't seem to find a solution for.

I have the following simple interface :

    public interface IDataProperty<T> 
{
   public T Value { get; set; } 
   public int BytesCount();
   public byte[] Serialize();
}

the struct which implements the interface above :

    public struct IntProperty : IDataPropery<int> 
{
    private int _value; 
    public int Value { get => _value; set => _value = value; }

    public int BytesCount()
    {
        return 4;
    }

    public byte[] Serialize()
    {
        return BitConverter.GetBytes(_value);
    }
    public IntDataProperty(int value) { _value = value; }
}

and a simple class to hold the values :

public class ValuesContainer  
{
   public IntProperty prop1;
   public IntProperty prop2;
}

I am trying to call the Serialize() method on both prop1 and prop2 in my Processor class, with no luck so far... :

public class Processor  
{
   public void ProccesData<T>(out T result) where T : ValuesContainer, new() 
    {
      result = new T();
        List<FieldInfo> dataFields = new List<FieldInfo>();
        result.GetType().GetFields().ToList().ForEach(field => { 
        if(field.FieldType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDataProperty<>)))
            {
                dataFields.Add(field);
            }
              });
         MethodInfo serializeMI = typeof(IDataProperty<>).GetMethod("Serialize");
         foreach(FieldInfo field in dataFields)
        {
            Console.WriteLine(field.Name);
            serializeMI.Invoke(field,null);
        }

    }
}

Running the code at this point gives me the following error :

'Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.'

I am aware that I need to get somehow to the instance behind the field variable, but have no idea how to do it. Does anyone know a good way of doing what i am trying to achieve using other methods, or only Reflection is the way to go, and if the latter - what solutions do I have ?

Thanks in advance to all of you.





mardi 19 avril 2022

How to use MakeGenericMethod with multiple parameters

I am trying to invoke a generic method using a type argument that is parsed at runtime from a string (user input). Here is my test code:

        MethodInfo method = typeof(GameManager).GetMethod(nameof(GameManager.SetPreference));
        MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { typeof(PlayerData.Preferences), typeof(bool) });
        genericMethod.Invoke(new GameManager(), new object[] { PlayerData.Preferences.WaitMode, true });

This fails with "ArgumentException: Incorrect length".

Here is the function I'm calling:

public void SetPreference<T>(PlayerData.Preferences preference, T value)
    {
        try
        {
            PlayerData.SetAttr(preference.ToString(), value);
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            return;
        }

        OnPreferenceChanged.Raise(preference);
    }

What am I doing wrong?





What is the worst-case time complexity of reflect.DeepEqual() in Go?

I tried to analyze the source code, but many other functions are called from within deepValueEqual(), and I must admit that the use of recursion is throwing me off in this case.

Is there any official documentation of the function's worst-case running time?





lundi 18 avril 2022

How to execute code that uses reflection during build in a maven project?

I have a maven project in which I try to execute code during build (ideally between compile and test phases, but I'm not there yet, for now I execute the code after goals execution).

For this purpose, I use :

<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>

My code is executed during build. However, it uses com.google.guava reflection, which does not seem to work as expected in this context.

Here is a MRE code :

package com.example;

import com.google.common.reflect.ClassPath;

import java.io.IOException;

public class LoadedClassesPrinter {

    public static void main(String[] args) throws IOException {
        ClassPath.from(ClassLoader.getSystemClassLoader())
                .getAllClasses()
                .stream()
                .forEach(o -> System.out.println(o.getName()));
    }

}

And here is a MRE pom.xml :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>maven-exec-reflection</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.1-jre</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <mainClass>com.example.LoadedClassesPrinter</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.example.LoadedClassesPrinter</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

When I execute the main class from my IDE or from the generated jar (with dependencies), it works : it prints a bunch of classes, including my LoadedClassesPrinter, as I expect.

...
com.google.j2objc.annotations.RetainedLocalRef
com.google.j2objc.annotations.RetainedWith
com.google.j2objc.annotations.Weak
com.google.j2objc.annotations.WeakOuter
com.example.LoadedClassesPrinter

But when I run mvn clean install assembly:single exec:java, the main method is executed, but it only prints a much smaller list of classes, which, to my surprise, does not include my LoadedClassesPrinter:

org.codehaus.classworlds.BytesURLConnection
org.codehaus.classworlds.BytesURLStreamHandler
org.codehaus.classworlds.ClassRealm
org.codehaus.classworlds.ClassRealmAdapter
org.codehaus.classworlds.ClassRealmReverseAdapter
org.codehaus.classworlds.ClassWorld
org.codehaus.classworlds.ClassWorldAdapter
org.codehaus.classworlds.ClassWorldReverseAdapter
org.codehaus.classworlds.ConfigurationException
org.codehaus.classworlds.Configurator
org.codehaus.classworlds.ConfiguratorAdapter
org.codehaus.classworlds.DefaultClassRealm
org.codehaus.classworlds.DuplicateRealmException
org.codehaus.classworlds.Launcher
org.codehaus.classworlds.NoSuchRealmException
org.codehaus.plexus.classworlds.ClassWorld
org.codehaus.plexus.classworlds.ClassWorldException
org.codehaus.plexus.classworlds.ClassWorldListener
org.codehaus.plexus.classworlds.UrlUtils
org.codehaus.plexus.classworlds.launcher.ConfigurationException
org.codehaus.plexus.classworlds.launcher.ConfigurationHandler
org.codehaus.plexus.classworlds.launcher.ConfigurationParser$1
org.codehaus.plexus.classworlds.launcher.ConfigurationParser
org.codehaus.plexus.classworlds.launcher.Configurator$1
org.codehaus.plexus.classworlds.launcher.Configurator
org.codehaus.plexus.classworlds.launcher.Launcher
org.codehaus.plexus.classworlds.realm.ClassRealm
org.codehaus.plexus.classworlds.realm.DuplicateRealmException
org.codehaus.plexus.classworlds.realm.Entry
org.codehaus.plexus.classworlds.realm.NoSuchRealmException
org.codehaus.plexus.classworlds.strategy.AbstractStrategy
org.codehaus.plexus.classworlds.strategy.OsgiBundleStrategy
org.codehaus.plexus.classworlds.strategy.ParentFirstStrategy
org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
org.codehaus.plexus.classworlds.strategy.Strategy
org.codehaus.plexus.classworlds.strategy.StrategyFactory

I found a set of configuration for exec-maven-plugin and I tried to use them but it never changed anything.

What am I doing wrong? Is there an easy way to execute code to list my classes using reflection during build? It does not have to be exec-maven-plugin and com.google.guava, I am open to other plugins and libraries.

(I use maven 3.8.3 and java 16)





Pass a method to another method as parameter using expression tree in c#

I have a method like public void MethodName(int prm). And i have another method like public void MethodName2(Action<int> prm).

My problem is that I have to create a expression tree that takes MethodName2 and run it with MethodName like MethodName2(MethodName). But I can't find a we to pass function to another function using expression trees. Can someone help me please?





dimanche 17 avril 2022

Get value of interface{ } without having access to type

How can I get the value of x as []interface{} ?

func main() {

    var x interface{} = SomeFunc()
    
    fmt.Println(x) // this prints [1 2].

    val := x.([]interface{}) // this will not work because '[]interface{}' is different type than 'a'

}

func SomeFunc() interface{} {
    // some type I dont have access to
    type a []interface{}

    var someArray a = make([]interface{}, 0)
    someArray = append(someArray, 1)
    someArray = append(someArray, 2)
    return someArray
}





jeudi 14 avril 2022

C# how to check if generic arguement is a real type?

Hello,

I have a code like the following:

IEnumerable<Type> types = new []
{
    typeof(MyService),
    typeof(ILogger<MyService>),
    typeof(ILogger<>),           // <-- that are the interesting lines
    typeof(IDictionary<,>)       // <-- that are the interesting lines
};

Now I want to filter all types, where the generic argument is not set

types
    .Where(t => t.IsGenericType is false || t.GetGenericArguments.All(at => /* is argument type a real type? */))
    .ToArray();

As shown in the example I have troubles to figure out if a type is just a placeholder or it is a real type.
I found it could work by proofing string.IsNullOrEmpty(a.FullName) is false but I think it´s not a really beautiful solution.
There must be something better. 🤞

Thank you for your help!





mardi 12 avril 2022

Using reflection on singleton object kotlin?

I have a use case where I need to use reflection to call method of my singleton class

Singleton class is as below

object Singleton {

fun calledFromReflection(){
    println("Successfull")
}
}

This is how I am using the reflection

val adsUtiltyCls: Class<*>? = Class.forName("com.xia.Singleton")
        val adsUtilityObj: Any? = adsUtiltyCls?.newInstance()
        if (adsUtilityObj != null) {
            val method: Method
            try {
                method = adsUtiltyCls.getDeclaredMethod("calledFromReflection")
                val value=method.invoke(adsUtilityObj)
                println("value   $value")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

I get the following error

java.lang.IllegalAccessException: void com.com.xia.Singleton.<init>() is not accessible from java.lang.Class<com.xia.RetargetActivity>




lundi 11 avril 2022

Obtaining an addressable copy of a reflect.Value

I want to add marshalling/unmarshalling to types that I accept, in a way similar JSON custom encoding/decoding. I have it all working great when the type implements a Marshal method (value receiver) and Unmarshal method (pointer receiver).

The Unmarshal method must obviously use a pointer receiver so that the new value is saved. I have been told that a Marshal method using a pointer (not value) receiver should also be allowed. The trouble with this is I am using a reflect.Value which is not always addressable.

Here's an edited extract of the code which panics:

  var v reflect.Value // passed in parameter

  t := v.Type()
  pt := reflect.TypeOf(reflect.New(t).Interface())

  if t.Implements(reflect.TypeOf((*Marshaler)(nil)).Elem()) {
    str, err = v.Interface().(Marshaler).MarshalXXX()
    // ... value receiver WORKS FINE

  } else if pt.Implements(reflect.TypeOf((*Marshaler)(nil)).Elem()) {
    str, err = v.Addr().Interface().(Marshaler).MarshalXXX()
    // ptr receiver gives PANIC value is not addressable

I tried creating a copy of v, but the copy is also not addressable which makes no sense to me:

    tmp := reflect.New(v.Type())
    tmp.Addr().Set(v)
    str, err = tmp.Interface().(Marshaler).MarshalXXX()

In case I have not explained this well here is an example on the Go Playground for you to try:

Also while I am here: Is there a better way to get the type of a pointer to a the type than in the assignment to pt above?





How to make sure instance of a class with a private constructor can not be created from outside of the class using Reflection?

I know that an instance of a class with a private constructor can be created using reflection but is there any way to make sure that the instance of the class can only be created within the same class using its own private constructor?

Let's take an example of a class Test, with a private constructor.

import java.lang.reflect.Constructor;

   import java.lang.reflect.InvocationTargetException;

   class Test   
   {

      private Test()  //private constructor
      {
      } 
   }

  public class Sample{

      public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
     {

       Class c=Class.forName("Test"); //specify class name in quotes

       //----Accessing private constructor
       Constructor con=c.getDeclaredConstructor();
       con.setAccessible(true);     
       Object obj=con.newInstance();
   }   
} 

My question is - is there any way to ensure that the instance of the class can only be created within the same class and not from outside using reflection or any other method?





How pass Type to Method

I have method like below:

public void Method<TEntity>()
{
    //do some works
}

Problem is here that i can't cat type to TEntity.

foreach (var type in types)
{
    //i want pass type as T to method
    Method<type>();
}

What is the recommended way of doing this?

Thanks in advance.





dimanche 10 avril 2022

PHP get params from function inside of Namespace

I'm trying to get the params (names) of a function that is stored within a namespace and class. I've tried ReflectionFunction, but I can only make that work without namespaces and classes. The function I'm trying to call is non-static, which doesn't make it much easier.

namespace app\http;

class Test {
   public function func(User $user, $id) {
     return $user;
   } 
}

I'm trying to get "user" and "id" from here. Does someone have a suggestion?





why my is overlaying on another div on small screen

enter image description here

Whenever I check the responsiveness and check it on the small screen my one div starts overlaying another div. I have tried the ```position : relative and overflow: hidden as well but it makes no sense call you please tell me what I have to do to stop it from being overlaying another div

my HTML code is :

<div class="container-grid">
      <div class="grid_upper">
        <h1 class="grid_Heading">My recent projects</h1>
        <div class="grid_para">
          Ask me a Question if you are unable to solve it.
        </div>
      </div>
      <div class="cardContainer1">
        <div class="container">
          <div class="row">
            <div class="col-sm">
              <div class="card h-200">
                <img
                  src="./istockphoto-1074239826-170667a.jpg"
                  class="card-img-top"
                  alt="..."
                />
                <div class="card-footer">
                  <small class="card_text_1">Business</small>
                  <small class="text-muted"> 3  mins</small>
                </div>
                <div class="card-body">
                  <h5 class="card-title">Card </h5>
                  <p class="card-text">
                    This is a wider card with supporting text below as a natural
                    lead-in to additional content. This content is a little bit
                    longer.
                  </p>
                </div>
                <div class="card-footer footerNo2">
                  <img class="shortImg" src="./istockphoto-1074239826-170667a.jpg" alt="">
                  <div class="FooterInsideContainer">
                    <small class="text"> Micheal Corleone</small>
                    <small class="text-muted"> Senior web developer</small>
                  </div>
                </div>
             
              </div>
            </div>
            <div class="col-sm">
              <div class="card h-200">
                <img
                  src="./istockphoto-1272685152-612x612.jpg"
                  class="card-img-top"
                  alt="..."
                />
                <div class="card-footer">
                  <small class="card_text_1">Business</small>
                  <small class="text-muted"> 3  mins</small>
                </div>
                <div class="card-body">
                  <h5 class="card-title">Card title</h5>
                  <p class="card-text">
                    This is a wider card with supporting text below as a natural
                    lead-in to additional content. This content is a little bit
                    longer.
                  </p>
                </div>
                <div class="card-footer footerNo2">
                  <img class="shortImg" src="./istockphoto-1074239826-170667a.jpg" alt="">
                  <div class="FooterInsideContainer">
                    <small class="text"> Micheal Corleone</small>
                    <small class="text-muted"> Senior web developer</small>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-sm">
              <div class="card h-200">
                <img
                  src="./photo-1473090826765-d54ac2fdc1eb.jpg"
                  class="card-img-top"
                  alt="..."
                />
                <div class="card-footer">
                  <small class="card_text_1">Business</small>
                  <small class="text-muted"> 3  mins</small>
                </div>
                <div class="card-body">
                  <h5 class="card-title">Card title</h5>
                  <p class="card-text">
                    This is a wider card with supporting text below as a natural
                    lead-in to additional content. This content is a little bit
                    longer.
                  </p>
                </div>
                <div class="card-footer footerNo2">
                  <img class="shortImg" src="./istockphoto-1074239826-170667a.jpg" alt="">
                  <div class="FooterInsideContainer">
                    <small class="text"> Micheal Corleone</small>
                    <small class="text-muted"> Senior web developer</small>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row my-3">
            <div class="col-sm-4">
              <div class="card h-200">
                <img
                  src="./creative-book-cover-design-vintage-260nw-1115305040.webp"
                  class="card-img-top"
                  alt="..."
                />
                <div class="card-footer">
                  <small class="card_text_1">Business</small>
                  <small class="text-muted"> 3  mins</small>
                </div>
                <div class="card-body">
                  <h5 class="card-title">Card title</h5>
                  <p class="card-text">
                    This is a wider card with supporting text below as a natural
                    lead-in to additional content. This content is a little bit
                    longer.
                  </p>
                </div>
                <div class="card-footer footerNo2">
                  <img class="shortImg" src="./istockphoto-1074239826-170667a.jpg" alt="">
                  <div class="FooterInsideContainer">
                    <small class="text"> Micheal Corleone</small>
                    <small class="text-muted"> Senior web developer</small>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-sm-8" style="background-color: white;">
              <div class="card card2 h-200" >
                <img style="width: 100%;"
                  src="./wide-view-image-young-woman-paddling-sup-board-calm-morning-sea-water-rear-view_254268-2063.jpg"
                  class="card-img-top"
                  alt="..."
                />
                <div class="card-footer laster">
                  <small class="card_text_1">Business</small>
                  <small class="text-muted"> 3  mins</small>
                </div>
                <div class="card-body">
                  <h5 class="card-title">Card title</h5>
                  <p class="card-text">
                    This is a wider card with supporting text below as a natural
                    lead-in to additional content. This content is a little bit
                    longer.
                  </p>
                </div>
                <div class="card-footer footerNo2_laster">
                  <img class="shortImg" src="./istockphoto-1074239826-170667a.jpg" alt="">
                  <div class="FooterInsideContainer">
                    <small class="text" style="color: black;"> Micheal Corleone</small>
                    <small class="text-muted"> Senior web developer</small>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      
        </div>
      </div>
    </div>
    <div class="Approach">
      <div class="app_head">
        <h1 class="main_approach_Heading">My approach</h1>
      </div>
      <div class="container">
        <div class="row row-cols-1 row-cols-md-3 g-4">
          <div class="col">
            <div class="card h-100">
              <!-- <img src="..." class="card-img-top" alt="..."> -->
              <h1 class="pic_char no1">1</h1>
              <div class="card-body">
                <h5 class="card-title">We will sit and talk drinking coffee</h5>
                <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
              </div>
              <div class="card-footer approach_footer">
                <div class="triangle arrow-up"></div>

              </div>
            </div>
          </div>
          <div class="col">
            <div class="card h-100">
              <!-- <img src="..." class="card-img-top" alt="..."> -->
              <h1 class="pic_char no2">2</h1>
              <div class="card-body">
                <h5 class="card-title">We will sketch some ugly Frameworks</h5>
                <p class="card-text">This card has supporting text below as a natural lead-in to additional content text below as a natural lead-in to additional content.</p>
              </div>
              <div class="card-footer approach_footer">
                <div class="app_circle">  </div>
              </div>
            </div>
          </div>
          <div class="col">
            <div class="card h-100">
              <!-- <img src="..." class="card-img-top" alt="..."> -->
              <h1 class="pic_char no3">3</h1>
              <div class="card-body">
                <h5 class="card-title">You will pay alot for my services</h5>
                <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
              </div>
              <div class="card-footer approach_footer">
                <div class="triangle arrow-up"></div>
               
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

and the CSS code is :


    .grid_upper {
      display: flex;
      flex-direction: column;
      width: 67%;
      margin: auto;
    }
    .grid_Heading {
      font-size: clamp(2em, 2.5vw, 7em);
      padding: 0.5em 0.21em 0em 0em;
      color: white;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
        Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    }
    .grid_para {
      color: white;
    }
    .container-grid {
      display: flex;
      position: relative;
      height: 160vh;
      overflow: visible;
      flex-wrap: wrap;
      background-color: #3e4245;
    }
    .cardContainer1 {
      position: relative;
    
      display: flex;
      flex-wrap: wrap;
      padding: 2em 0em;
      width: 70%;
      margin: auto;
    }
    .cardContainer2 {
      position: relative;
    
      display: flex;
      flex-wrap: wrap;
      padding: 2em 0em;
      width: 70%;
      margin: auto;
    }
    .card {
      background-color: #252728;
      border: none;
      border-radius: 20px;
      height: 100%;
    }
    .card2 {
      background-color: white;
    }
    .card2 .card-title {
      color: black;
    }
    .card2 .card-text {
      color: grey;
    }
    
    .card-title {
      color: white;
    }
    .card-text {
      color: rgba(255, 255, 255, 0.522);
    }
    .card-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: rgba(255, 255, 255, 0.522);
      background-color: #252728;
      /* background-color: red; */
      margin: none;
      border: none;
    }
    .card_text_1 {
      color: rgba(255, 255, 0, 0.659);
    }
    .card-img-top {
      width: 100%;
      height: 25vh;
      object-fit: cover;
    }
    .shortImg {
      height: 40px;
      width: 40px;
      border-radius: 50%;
    }
    .footerNo2 {
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      /* flex-direction: column; */
      padding: 1em 1em;
      /* background-color: aqua; */
    }
    .footerNo2_laster {
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      background-color: white;
    }
    .FooterInsideContainer {
      display: flex;
      flex-direction: column;
      padding: 0em 1em;
    }
    .laster {
      background-color: white;
    }
    .laster .card_text_1 {
      color: skyblue;
    }
    .Approach {
      position: relative;
      /* overflow: hidden; */
      height: 100vh;
      width: 100%;
      margin-top: 10em;
    }
    .app_head {
      padding: 7em 5em;
      display: flex;
      font-weight: bold;
      /* background-color: red; */
    }
    .main_approach_Heading {
      font-size: clamp(1.5rem, 10.5vw, 4rem); 
      font-family: "Roboto", sans-serif;
      margin: auto;
      text-align: center;
    }
    .pic_char {
      background-repeat: repeat;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      /* margin-top: 200px; */
      text-align: center;
      font-weight: bold;
      text-transform: uppercase;
      /* font-family: 'Times New Roman', Times, serif; */
      font-weight: 800;
      -webkit-font-smoothing: antialiased;
    }
    .no1 {
      background-image: url("./istockphoto-1288917639-170667a.jpg");
      font-family: "Montserrat Alternates", sans-serif;
      font-size: 13em;
    }
    .no2 {
      background-image: url("./polygonal-square-background-black-blue-purple-vector-21357114.jpg");
      /* font-family: 'Anton', sans-serif; */
      font-size: 12em;
    }
    .no3 {
      background-image: url("./android-marshmallow-6-hd-orange-yellow-and-gray-blocks-illustrarion-wallpaper-preview.jpg");
      font-size: 12em;
    }
    .Approach .card {
      display: flex;
      background-color: white;
      color: black;
      /* width: 50%; */
    }
    .Approach .card-body {
      display: flex;
      flex-direction: column;
      text-align: center;
      align-items: center;
      justify-content: center;
      padding: 0em 4em;
      /* background-color: pink; */
    }
    .Approach .card-title {
      color: black;
      font-weight: 700;
      font-size: 1.4em;
      font-feature-settings: "vrt2";
    }
    .Approach .card-text {
      color: grey;
      text-align: center;
    }
    .approach_footer {
      background-color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      color: grey;
    }
    .arrow-up {
      width: 0;
      height: 0;
      border-left: 20px solid transparent;
      border-right: 20px solid transparent;
      border-bottom: 20px solid white;
      box-shadow: -1px -1px 10px -2px rgba(0, 0, 0, 0.5);
    }
    .app_circle{
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background-color: white;
      box-shadow: -1px -1px 10px -2px rgba(0, 0, 0, 0.5);
    
    }





samedi 9 avril 2022

Java cannot get values with method call using reflection in a loop

Here is the code: fyi this is someones else's code that I am working with:

Here itemsList has size 3 and the selectedColumns has size 10, This code is used to generate 3 rows of a table where each row has 10 columns in pdf format itext library 5.5.10.

for (int i = 0; i < itemsList.size(); i++) {
            for (int j = 0; j < selectedColumns.size(); j++){
                try{
                    Method method = itemsList.get(i).getClass().getMethod("get"+selectedColumns.get(j).getCol());
                    Debug.e("NewPDF : method name"+ String.valueOf(itemsList.get(i).getClass().getMethod("get"+selectedColumns.get(j).getCol())));
                    String value;
                    if(method.invoke(new CloudHolder(), null) == null){
                        value = "";
                        Debug.e("NewPDF : value from loop null ");
                    }else{
                        value = String.valueOf(method.invoke(new CloudHolder(),null)) ;
                        Debug.e("NewPDF : value from loop " + value);
                    }

                    c1 = new PdfPCell(new Phrase(value, smallFont));
                    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    c1.setVerticalAlignment(Element.ALIGN_CENTER);
                    c1.setMinimumHeight(30f);
                    table.addCell(c1);
                    table.writeSelectedRows(i,  i+1, 70, currentpos, canvas);
                }catch (NoSuchMethodException e){
                    Debug.e("NewPDF : method not found");
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                    Debug.e("NewPDF : Illegal access | Invocation Exp" + e.getMessage());

                }

                if (currentpos <= 149) {
                    document.newPage();
                    document.setPageSize(pageSize);
                    document.add(pageSizes);
                    currentpos = 1200;

                }
            }


        }

The Method name is correct as the getter method as usual has "get" written before the variable name, together making the function name. but when I invoke the method the values are always null, what am I missing.

Also I am new to itext libary for some reason the table.writeSelectedRows prints nothing,and the if statement block if (currentpos <= 149) is also beyond me. Some help with those parts of the code is also appreciated.

update:

here is a proof of concept that I wrote which you can try and run:

public class Reflection {

    public static void main(String[] args) {
        ArrayList<PDFColumn> selectedColumns = new ArrayList<>();
        ArrayList<CloudHolder> itemsList = new ArrayList<>();
        selectedColumns.add(new PDFColumn("Carat",true));
        selectedColumns.add(new PDFColumn("Category",true));
        selectedColumns.add(new PDFColumn("Cert",true));
        selectedColumns.add(new PDFColumn("Date",true));
        selectedColumns.add(new PDFColumn("Design_code",true));
        selectedColumns.add(new PDFColumn("Dia_Wt",true));
        selectedColumns.add(new PDFColumn("Dia_color",true));
        selectedColumns.add(new PDFColumn("Dia_desc",true));
        selectedColumns.add(new PDFColumn("Dia_pcs",true));
        selectedColumns.add(new PDFColumn("Doc_no",true));
        CloudHolder holder = new CloudHolder();
        holder.setCarat(1f);
        holder.setCategory("Test cat");
        holder.setCert("Test cert");
        holder.setDate("Test date");
        
        itemsList.add(holder);
        itemsList.add(holder);
        itemsList.add(holder);
        for (int i = 0; i < itemsList.size(); i++) {
            for (int j = 0; j < selectedColumns.size(); j++){
                try{
                    Method method = itemsList.get(i).getClass().getMethod("get"+selectedColumns.get(j).getCol());
                    System.out.println("NewPDF : method name"+ String.valueOf(itemsList.get(i).getClass().getMethod("get"+selectedColumns.get(j).getCol())));
                    String value;
                    if(method.invoke(itemsList.get(i), null) == null){
                        value = "";
                        System.out.println("NewPDF : value from loop null ");
                    }else{
                        value = String.valueOf(method.invoke(new CloudHolder(),null)) ;
                        System.out.println("NewPDF : value from loop " + value);
                    }

                }catch (NoSuchMethodException e){
                    System.out.println("NewPDF : method not found");
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                    System.out.println("NewPDF : Illegal access | Invocation Exp" + e.getMessage());

                }


            }


        }


    }
}

PDFColumn

public class PDFColumn {
    private String cols;
    private boolean selected;

    public PDFColumn(String cols, boolean selected) {
        this.cols = cols;
        this.selected = selected;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public String getCol() {
        return cols;
    }

    public void setCols(String cols) {
        this.cols = cols;
    }
}

CloudHolder

public class CloudHolder implements Serializable, Comparator<CloudHolder> {

    private String Item_Code;
    private int Qty;
    private float Gross_Wt;
    private float Net_Wt;
    private float Dia_Wt;
    private float St_Wt;
    private float Gold_Oth_Wt;
    private float Tag_Price;
    private float Carat;
    private float Dia_pcs;
    private float Ot_st_Wt;
    private float Silver_Wt;
    private float Pearl_wt_pcs;
    private float Price_2;

    private String Category;
    private String ItemType_Name;
    private String Location_Name;
    private String Item_Description;
    private String Img_url;
    private String scan_date;
    ////////// new filed added//////////


    private String Design_code;
    private String Dia_color;
    private String Tray_no;
    private String Dia_desc;

    private String St_desc;
    private String Doc_No;
    private String Date;
    private String Season;
    private String Sieve;
    private String Purity;
    private String Time;
    private String Size;
    private String Shape;
    private String Cert;
    private int index;
    private String zone;
    private String Type;
    private String MainBrand;
    private String SubBrand;
    private String MakingCharge;

.... default getters setters

I have set the values for Carat,Category,Cert,Date but none are retrieved.

Logs:

NewPDF : method namepublic float leetcode.CloudHolder.getCarat()
NewPDF : value from loop 0.0

NewPDF : method namepublic java.lang.String leetcode.CloudHolder.getCategory()
NewPDF : value from loop null

NewPDF : method namepublic java.lang.String leetcode.CloudHolder.getCert()
NewPDF : value from loop null

NewPDF : method namepublic java.lang.String leetcode.CloudHolder.getDate()
NewPDF : value from loop null




vendredi 8 avril 2022

Add dynamic type into loaded non-dynamic assembly

Using AssemblyBuilder, I can create dynamic assemblies that contain dynamic types.

Is it possible to add a dynamic type to a non-dynamic assembly - i.e. a real assembly that is currently loaded?

For example, add a dynamic type into Assembly.GetExecutingAssembly()?





jeudi 7 avril 2022

c# reflection for input string validation

I am new to C#. have a few doubts about using reflection for input string validation. below is the code .

here we pass string value as input and get properties of the string. it's actually Char and Int. So for Char property , in the line " var charVal = prop.GetValue(inputStr,new Object[] {0}); " I want know what exactly they are doing, are they trying to get the Char property value from object (input str) and validating if that is null .

and in the TryParse line, im getting only 1st character of the string using GetValue(inputStr,new Object[] {0}) . how can i get the complete string instead of getting characters one by one using GetValue().

var properties = inputStr.GetType().GetProperties(); foreach(PropertyInfo prop in properties) { var type = Nullable.GetUnderlyingType(prop.PropertyType)??prop.PropertyType;

if(type==typeof(char)
{
  char charTxt ='a';
  var charVal = prop.GetValue(inputStr,new Object[] {0});
  if(charVal == null)
    continue;
  if(char.TryParse(prop.GetValue(inputStr,new Object[] {0}).ToString()), out charTxt))
  {
  }
  else{
    return "invalid"
  }
}

}





mardi 5 avril 2022

Spring custom annotation validate http header with reflection

I have an endpoint secured with token given in the header. I would like to create my custom annotation so when I annotate the controller method the validation token goes first and then if the token was accurate do the rest of the method. I tried do it with interceptor and it worked but I want to do it using reflection to have custom annotation. I can share some of my code snippet but there is not a lot of code because I couldn't find some that tells me how to get token from header and validate it. And I'm a noob in reflection.

Custom Annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TokenValidation {
  String token() default "";
}

Controller Class

 @TokenValidation
 @PostMapping("/endpoint")
 public ResponseEntity createComplianceDirectory(@RequestBody ComplianceDirRequest request) {
    return ResponseEntity.status(HttpStatus.OK).build();
 }

Reflection class

    @Value("${token}")
private String token;

private Reflections reflections;

public Reflection() {
    reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("com.sampleapp.controller"))
            .setScanners(new FieldAnnotationsScanner()));
    setReflections();
}

public void setReflections() {
    Set<Method> methods = reflections.getMethodsAnnotatedWith(TokenValidation.class);
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String requestToken = request.getHeader("Authorization");
    }
}

Could someone tell me:

  1. How to register that reflection class in spring boot to be invoked when the controller method is called.
  2. Is it a good way in my reflection class to retrieve the header ?




lundi 4 avril 2022

Use reflection to extend a class marked internal?

I am using a library which has a class i want to extend to add some functionality, but that class is marked internal. Is there some way to use reflection to be able to extend that class? or is my only option to fork the repo and do it that way?





dimanche 3 avril 2022

Modify fields with reflection (Java 8) [closed]

Why is it possible to use Reflections in Java 8 to modify only the second example and not the first example? Can anyone help :) .-.

public class Test {

    private String name = "Hans";

}

---------------------------------------------------------

public class Test {

    private String name;

    public Test() {
        name = "Hans";
    }

}

----------------------------------------------
Test test = new Test();

Field field = Test.class.getDeclaredField("name");
field.setAccessible(true);
field.set(test, "Paul");




samedi 2 avril 2022

Java: make static methods of one class mirror instance methods of another class

I have a POJO like this:

public class Foo {
    private String bar1;
    private String bar2;
    //...

    public String getBar1() { return bar1; } 
    public void setBar1(String bar1) { this.bar1 = bar1; }
    public String getBar2() { return bar2; } 
    public void setBar2(String bar2) { this.bar2 = bar2; }
    //...
}

As an alternative to Java reflection (which is quite slow in general), I would like to define a class with static methods like this:

public class FooStatic {

    public static String getBar1(Foo foo) { return foo.getBar1(); } 
    public static void setBar1(Foo foo, String bar1) { foo.setBar1(bar1); }
    public static String getBar2(Foo foo) { return foo.getBar2(); } 
    public static void setBar2(Foo foo, String bar2) { foo.setBar2(bar2); }
    //...
}

which enforces the creation/deprecation of a static method every time the Foo class is updated. For example, if the field bar2 is deleted in FooStatic, then the static methods getBar2() and setBar2() in FooStatic should be identified by the compiler to be removed. If a new variable bar3 is added to Foo with getters and setters, the compiler should enforce the creation of new static methods getBar3() and setBar3() in FooStatic. Moreover, I have multiple POJOs, and would like a solution which scales. Is this possible?





Convert List

I'm trying to convert a string delimited by a comma to a list of some type.

private static void SetPropertyValue(this object obj, PropertyInfo propInfo, object value)
{
    if (propInfo.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(propInfo.PropertyType))
    {
        var listType = propInfo.PropertyType.GetCollectionType();
        var listValue = value.ToString().Split(',').Select(x => Convert.ChangeType(x, listType, null)).ToList();

        propInfo.SetValue(obj, listValue, null);
    }
    
    //....
}

public static Type GetCollectionType(this Type type)
{
    foreach (Type interfaceType in type.GetInterfaces())
    {
        if (interfaceType.IsGenericType &&
            interfaceType.GetGenericTypeDefinition()
            == typeof(IList<>))
        {
            return type.GetGenericArguments()[0];
        }
    }

    throw new ArgumentException("Message is irrelevant");
}

Splitting the string and converting each value with Convert.ChangeType works well, but creates a List<object>. I need some way of generating a List<PropType> in order for the SetValue call to work correctly.

If you were to run this code with a List<string> property, you would receive an ArgumentException as the List<object> cannot be converted to a List<string>.