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>.