lundi 16 décembre 2019

Using Kotlin reflection sealedSubClasses property in Android release build

When I am trying to use the sealedSubClasses attribute of a reified class in Kotlin, it only works in my debug and not in my release build. I guess this is a problem with ProGuard, but I don't know how to fix this. I already tried keeping all classes in the module where the sealed class is, but I am having no luck with this. The sealedSubClasses property always returns an empty list.





dimanche 15 décembre 2019

Adding universal getter/setter for all calls to child object/Generating methods at runtime

Preamble: I'm working on implementing a system where a developer can specify on object of type T which has N number of properties.

What I'm trying to accomplish:

I'd like to be able to provide more concrete control over how these properties are set and retrieved. This is difficult because of the limitless number of configurations possible.

Solutions I'm pursuing:

  • Is it possible to set getters dynamically?
  • Either through attributes? Generate the methods after the fact during construction like :
    foreach(var property in typeOf(T).GetProperties()) 
    {
         //dynamically generate getter method which returns this property.
    }
  • Possibly wrap type T in a container object which has the type as one of its properties. Then set up some type of special getter for that.

Why I want to do this:

Currently all the types for T get converted based on Typecode. Allowing people using this library to easily parse in values from various sources (databases, text files, app configs, etc.) as properties of type T. The point being to deliver these properties as type safe values rather than magic strings.

This is the impetus for wanting to use reflection for this but I could see numerous other applications for this I would imagine.

I could just say "Hey make all of your types nullable." so that it would be easy to determine which properties have been set in type T. I'd like to abstract away even that though.

The other option for this would be "Make sure you understand that certain types have default values. Be certain you're ready to accept those values, or set default values of your own (including making it nullable and setting it to null if so desired). Essentially trusting this to the developer rather than abstracting it. <==== This is what I'm currently doing.

Being able to dynamically generate methods, especially getters and setters, dynamically via reflection or a combination of reflection and C# Actions would be incredibly valuable. Any insight or ideas would be greatly welcome. Either ways of accomplishing the solutions I'm pursuiing or another idea which achieves the same ends.





Java: can't catch exception with getConstructor()

I wrote an abstract class "Card" with two child classes called "Sticker" and "PlayingCard". The class "PlayingCard" has an object of an enum called "Color" attribute that basically says what type of card it is (hearts, spades, ...). In this enum, i have a method that returns an object based on a string: if i pass it the string "spades", it'll return an object that contains SPADES. If the string being passed to it doesn't exist as a card type (so not hearts, spades,...), it throws a self made "TypeUnknownException". This exception just calls its super(String message).

Now, when in a different class that reads a file and makes Card objects:

Card c= (Card) Class.forName(one).getConstructor(String.class, double.class).newInstance(two, three);

With one being a string from the txt file (that always will be an implemented class name like Sticker or Playingcard, two being a string taken from the txt file (should be a type of card like spades, but can be different, which should throw the exception, with this string as the message) and three being a parsed double from the txt file.

This would either call the constructor from Sticker or PlayingCard. When it calls the constructor from PlayingCard, it should be able to throw my "TypeUnknownException", so i can catch it to add it to a string of error messages to print out at the end. However, when i try to catch that exception, the compiler says it's never thrown. I get that it's because it doesn't yet know that it can call a constructor that throws my exception, but is there a way to catch that, and only that exception (no catch all, it has to throw other exceptions)?

For reference: code in the PlayingCard class:

public PlayingCard(String col, double worth) throws TypeUnknownException{
   this(col,(int)worth);
}

PlayingCards only take ints as its worth, but since the class Card has to take a double, there's the above extra constructor

public PlayingCard(String col, int w) throws TypeUnknownException{
    this.color= Color.getColorWithName(col.toUpperCase());
    this.worth= w;}

and the getColorWithName method in the enum Color:

public static Color getColorWithName(String name) throws TypeUnknownException{
    if(name.equalsIgnoreCase("Spades")){return SPADES;}
    else if(name.equalsIgnoreCase("Hearts")){return HEARTS;}
    else if(name.equalsIgnoreCase("Clovers")){return CLOVERS;}
    else if(name.equalsIgnoreCase("Tiles")){return TILES;}
    else throw new TypeUnknownException(name);
}

Something else that might be helpful: When i added a print in the constructor of the exception, it was able to print the name of the type of card that doesn't exist. So the exception is definitely being thrown, i just don't know how to catch it.





I need some information regarding RtlCreateProcessReflection from ntdll

I wanna get some information regarding the usage of this function. I hope someone can help me out because its not documented at all from what I found. The question may rise up why I don't use PssCaptureSnapshot which can fullfill a similar job. It has todo with security reasons why I want to use RtlCreateProcessReflection instead of PssCaptureSnapshot.

RtlCreateProcessReflection((HANDLE process_handle, ULONG flags, PVOID start_routine,
    PVOID start_context, HANDLE event_handle, PRTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION reflection_information));

It is self explanatory for myself what most of the arguments are there for but, the exception is with flags, start_routine, start_context, event_handle. I can imagine what start_routine would be but still I can't wrap my hand around those or what flags the argument "flags" would actually take.

I hope someone can help me out. Thanks for reading.





Spring Annotations are Missing from Class Object

I'm writing a plugin that scans my project's code on compile-time and finds the controllers to make sure they have some other custom annotation that I've created.

For some reason, all of Spring's annotations don't appear in the annotations array on

Class<?> clazz = classInfo.load();
Annotation[] annotations = clazz.getAnnotations();

Why are the spring annotations missing from this array? And where can I find them?

Here's my relevant code:

URL[] urls;
List<URL> listOfURL = new ArrayList<>();
SourceSetContainer ssc = getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();
File classesDir = ssc.getByName("main").getOutput().getClassesDir();
listOfURL.add(classesDir.toURI().toURL());
urls = listOfURL.toArray(new URL[0]);
final ClassLoader loader = new URLClassLoader(urls);
ClassPath classpath = ClassPath.from(loader); // scans the class path used by classloader
for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClassesRecursive(packageName)) {
    if (classInfo.getName().toLowerCase().contains("controller")) {
        Class<?> clazz = classInfo.load();
        if (clazz.isAnnotationPresent(RestController.class)) {
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                doSomething(clazz, method);
            }
        }
    }
}




samedi 14 décembre 2019

gRPC and ASP.NET Core: serverside reflection

I've been trying to implement the concepts of serverside reflection described in [https://github.com/grpc/grpc/blob/master/doc/server-reflection.md ] and for C# [https://github.com/grpc/grpc/blob/master/doc/csharp/server_reflection.md ] in the implementation of ASP.NET Core. You have to somehow configure Kestrel to enable Reflection first. I just don't succeed and have to give up. Does somebody know how to enable serverside reflection in ASP.NET Core with Kestrel? Or even better has a complete working example of serverside reflection in C# ASP.NET Core?





vendredi 13 décembre 2019

Use Reflection to generate 2 generic parent classes and 2 child classes that are dependent upon each other

I want to use reflection to generate 2 classes from 2 generics. The 2 classes to be generated are dependent upon each other as parameters to the 2 generic parents.

this example uses two generic classes:

    Data.Row<T,TABLE_TYPE>
    Data.Table<T, ROW_TYPE>

After generating AssemblyBuilder and ModuleBuilder, I load two type builders.

    TypeBuilder rowTypeBuilder = moduleBuilder.DefineType("MachineData." + dataTypeName + "Row",
               TypeAttributes.Public |
               TypeAttributes.Class |
               TypeAttributes.AutoClass |
               TypeAttributes.AnsiClass |
               TypeAttributes.BeforeFieldInit |
               TypeAttributes.AutoLayout,
               null);
    TypeBuilder tableTypeBuilder = moduleBuilder.DefineType("MachineData." + dataTypeName + "Table",
               TypeAttributes.Public |
               TypeAttributes.Class |
               TypeAttributes.AutoClass |
               TypeAttributes.AnsiClass |
               TypeAttributes.BeforeFieldInit |
               TypeAttributes.AutoLayout,
               null);

I then create the generic parent types

     Type rowParentType = typeof(Data.Row<,>).MakeGenericType(dataType, tableTypeBuilder);
     Type tableParentType = typeof(Data.Table<,>).MakeGenericType(dataType, rowTypeBuilder);

If I set the parents, as below, I get an exception when calling 'CreateType'

        rowTypeBuilder.SetParent(rowParentType);
        tableTypeBuilder.SetParent(tableParentType);
        // DefineConstructor code removed for clarity
        rowTypeBuilder.CreateType();
        tableTypeBuilder.CreateType();

I have tried TypeResolver to both save and load the assembly as well attempting to Create the dependent class in the resolver event handler.

I'm stuck. I was hoping reflection might be a better option than T4 templates or handwriting the code. It creates the assembly quickly and is easy to debug compared with T4 templates.