jeudi 30 avril 2020

How do I implement a factory method for objects created using reflection?

I have created a framework for automated testing that takes a Cucumber file and a page object and uses glue code to run automated tests. That glue code relies on reflection to instantiate elements on a web page in real time, like so:

/**
 * Returns a PageElement object for a given elementName string from current page. Gets current page reference, replaces page name space characters qith '_'
 * 
 * @param elementName String name of requested element
 * @return PageElement the requested element
 * @throws PageNotFoundException if no page object found or defined.
 * @throws NoSuchElementException if element is not found or defined.
 */
public static PageElement getElement(String elementName) throws NoSuchElementException, PageNotFoundException {
    Page page = PageManager.getPage();
    elementName = elementName.replaceAll("\\s+", "_").toLowerCase();
    Method pageElementName = null;
    try { // Create a Method object to store the PageElementwe want to exercise;
        pageElementName = page.getClass().getMethod(elementName);
    } catch (NoSuchMethodException e) {
        String errorMessage = StringUtils.format("Element {} is not defined for the page object {}. Make sure you have spelled the page object name correctly in your Cucumber step definition and in the page object.", elementName, page
                .getClass().getSimpleName());
        log.error(errorMessage);
        throw new NoSuchElementException(errorMessage, e);
    }
    PageElement element = null;
    try {  // Invoke the creation of the PageElement and return it into a variable if no exception is thrown.
        element = (PageElement) pageElementName.invoke(page);
        log.trace("PageElement Name: " + pageElementName.getName());
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        String errorMessage = StringUtils.format("PageElement {} could not be found on Page {}. Please ensure the element is defined on the page.", pageElementName.getName(), page.getName());
        log.error(errorMessage);
        throw new NoSuchElementException(errorMessage);
    } 

    return element;
}

If I need to return something like a drop down object which has more methods than a standard object, I do so by using a method that casts the returned object:

/**
 * Returns the Dropdown associated with the element name on the currently active
 * page.
 * 
 * @param elementName String the name of the element to be returned
 * @return Dropdown the dropdown associated with the element name on the currently active page
 * @throws NoSuchElementException if the element cannot be found
 * @throws PageNotFoundException if the page cannot be found
 */
public static Dropdown getElementAsDropdown(String elementName) throws SentinelException {      
    return (Dropdown) getElement(elementName);
}

Currently I have three drop down objects, and they all are defined differently inside of a page object:

public Dropdown state_dropdown() { return new Dropdown(ID, "state"); }
public MaterialUISelect age_dropdown() { return new MaterialUISelect(XPATH, "//*[@id=\"demo-simple-select\"]"); }
public PrimeNGDropdown city_dropdown() { return new PrimeNGDropdown(XPATH, "//p-dropdown[1]"); }

I want to be able to define all three drop downs in the Page object as Dropdown and have the code figure out which one it is when the object is created. The reason for this is I want to make the page object creation as foolproof as possible, as most testers using the framework are not very technically savvy.

I feel like I need a factory method to do this, but I cannot figure out where it goes in my code. Does it go in the getElement code? Does it go in the Dropdown object code? Am I thinking about this all wrong and there is another solution I should be using? I'm at a loss despite having bounced this off a couple of other developers.





Getting the type of Interface in Java

Currently, I am learning Java on Hyperskill, there is one question that I need help and clarification.

You need to implement method getComparatorType(Class) in ComparatorInspector class. The method should examine provided class and return Type object that corresponds to the type parameter that parameterizes Comparable interface the class implements. Consider the example:

class MyInt implements Comparable<Integer> {
    // Implementation omitted 
}

// Method to implement
Type type = ComparatorInspector.getComparatorType(MyInt.class);

System.out.println(type.getTypeName());
// prints: java.lang.Integer since MyInt implements Comparable with Integer parameter type

The method should:

  1. Return type parameter for Comparable interface class implements
  2. Return null if Comparable interface does not have type parameter
  3. Should not produce compile-time warnings
  4. Compile-time error should arise if class not implementing Comparable is provided as input value
  5. No 'rawtype' warnings should remain or be suppressed
  6. Method getComparatorType should be generic You are free to correct method's type signature if needed.

My code so far:

public static <T extends Comparable<?>> Type getComparatorType(Class<T> clazz) {
        // Add implementation
        // Print type name
        if (clazz.getGenericInterfaces().length == 0) {
            return null;
        }
        Type t = null;
        Type[] types = clazz.getGenericInterfaces();
        for (Type type : types) {
            if (type instanceof ParameterizedType) {
                t = ((ParameterizedType) type).getActualTypeArguments()[0];
            }
        }
        return t;
    }

I think the only problem I have here is the parameter type in the method signature. As far as I understand, the type in the method signature will be used in the parameter of this method and this type T should extend Comparable. But there is a flaw somewhere in the method signature, hope someone can help. I'm much appreciated.





persisting exception class property as json with subclass and superclass

I have the following exception Hierarchy:

public class C extends B {

    public C(final String message) {
        super(message);
    }
}

public abstract class B extends A {

    public B(final String message, final Throwable throwable) {
        super(message, throwable);
    }

    public B(final String message) {
        super(message);
    }
}

public class A extends RuntimeException {

    private boolean bypassable;

    public A(final String message) {
        super(message);
    }

    public A(final String message, final Throwable throwable) {
        super(message, throwable);
    }

    public boolean isBypassable() {
        return bypassable;
    }

    public void setBypassable(final boolean bypassable) {
        this.bypassable = bypassable;
    }
}

In my aspect advice class I am catching exception of type A and setting the bypassable value. Please note I am not catching the specific exception of type C:

@Aspect
@Component
public class ByPassableExceptionAspect {

    @Around("@annotation(...)")
    public void handle(final ProceedingJoinPoint pjp) throws Throwable {
        try {
            pjp.proceed();
        } catch (A exception) {
            a.setByPassable(true);
            }
        } catch (Throwable t) {
            throw t;
        }
    }
}

I need to persist the throwable information into database as json so I have this serializer class:

private class ThrowableJsonSerializer extends JsonSerializer<Throwable> {
    @Override
    public void serialize(final Throwable value,
                          final JsonGenerator gen,
                          final SerializerProvider serializers) throws IOException {
        writeThrowable(someOtherMethod(value), gen);
    }

    private void writeThrowable(final Throwable value,
                                final JsonGenerator gen) throws IOException {
        gen.writeStartObject();
        gen.writeFieldName("class");
        gen.writeString(value.getClass().getName());

        writeBypassableIfExists(value, gen);

        if (nonNull(value.getCause())) {
            gen.writeFieldName("cause");
            writeThrowable(value.getCause(), gen);
        }
        gen.writeEndObject();
    }

    private void writeBypassableIfExists(final Throwable throwable, final JsonGenerator gen) throws IOException {
        final Field bypassableField = ReflectionUtils.findField(throwable.getClass(), "bypassable"); //Spring Framework ReflectionUtils
        if (nonNull(bypassableField)) {
            bypassableField.setAccessible(true);
            gen.writeFieldName("bypassable");
            gen.writeString(String.valueOf(ReflectionUtils.getField(bypassableField, throwable)));
        }
    }
}

The issue I have is with the bypassable attribute. Although I set the value as true in my aspect code, it gets persisted as false in the database.

I think it is because I am calling writeThrowable() with cause each time and somehow the subclass C has reference to bypassable as false. When I run in debug, I get bypassable is written twice.

I am looking for some help to write bypassable field correctly. I am not sure how to filter on the Cause that has true. Perhaps need to filter on the superclass reference one? Would appreciate your help.

Json:

[
  {
    "cause": {
      "cause": {
        "class": "com.exception.C",
        "message": "blah blah",
        "bypassable": "true"
      },
...




How to create and set primitive in Golang using reflect

I want to test how my function setFieldValue() works.

func main() {

    value := uint64(0x36)
    resType := reflect.TypeOf(uint8(0))
    expectedRes := uint8(0x36)

    res := uint8(0)
    setFieldValue(reflect.ValueOf(&res).Elem(), resType.Kind(), value)

    if res == expectedRes {
        fmt.Println("voila")
    } else {
        fmt.Println("nuts")
    }
}

func setFieldValue(field reflect.Value, fieldKind reflect.Kind, fieldValue uint64) {
    switch fieldKind {
    case reflect.Uint8:
        field.SetUint(fieldValue)
    }
}

But I don't want res variable also has type TypeOf(uint8(0)). If I create res as

        res := reflect.New(resType)
        setFieldValue(res, resType.Kind(), value)

it doesn't work because res is unaddressable.

What is the correct way to create variable using reflect and then to set its value in some func?

Or how can I get the instance of newly created variable?





How do I get instance of class based on inheritance in Java/Groovy

I have the following interface inheritance scheme:

Category -> PortalCorp | Portal365

And the following interfaces:

Oracle | MsSql | PostgreSql

And finally, concrete singleton classes (only PortalCorp for simplicity):

class OracleQueryGetterPortalCorp extends DefaultQueryGetterPortalCorp implements PortalCorp, Oracle

class MssqlQueryGetterPortalCorp extends DefaultQueryGetterPortalCorp implements PortalCorp, MsSql

class PostgresQueryGetterPortalCorp extends DefaultQueryGetterPortalCorp implements PortalCorp, PostgreSql

I'm writing a function to get a concrete instance of a class. As a parameter we pass PortalCorp or Portal365 class. I guess it can be accomplished based on inheritance criteria

def <T extends Category> T getImpl(Class<T> category)
{
        Category queryGetter

        if (DDLTool.isOracle())
        {
            queryGetter = //here we need to return first instance of class which implements category (parameter either PortalCorp or Portal365) and Oracle
        }
        else if (DDLTool.isMSSQL())
        {
            queryGetter = //here we need to return first instance of class which implements category (parameter either PortalCorp or Portal365) and MsSql

        }
        else if (DDLTool.isPostgres())
        {
            queryGetter = //here we need to return first instance of class which implements category (parameter either PortalCorp or Portal365) and PostgreSql
        }

        return queryGetter

}

What's the best way to do that? Thanks in advance





mercredi 29 avril 2020

In C#, is there any way to reduce these 1 List and two Dictionaries to a single collection, possibly using reflection?

Currently I have the following code:

    using AddFunction = Func<MyDictionary, object, MyDictionary>;

    class MyDictionary {
        public const string AFile = "A.xml";
        public const string BFile = "B.xml";
        public const string CFile = "C.xml";
        public const string DFile = "D.xml";

        private static readonly List<string> fileList = new List<string> { AFile, BFile, CFile, DFile };

        public static readonly Dictionary<string, Type> documentTypeByFileName = new Dictionary<string, Type> {
            {AFile, typeof(ADocument)},
            {BFile, typeof(BDocument)},
            {CFile, typeof(CDocument)},
            {DFile, typeof(DDocument)},
        };

        private static readonly Dictionary<string, AddFunction> functionByFileName = new Dictionary<string, AddFunction> {
                {AFile, (@this, obj) => @this.AddA((A)obj)},
                {BFile, (@this, obj) => @this.AddB((B)obj)},
                {CFile, (@this, obj) => @this.AddC((C)obj)},
                {DFile, (@this, obj) => @this.AddD((D)obj)}
        };
    }

As you can see, it contains 3 different collections.

We need fileList to maintain the order.

We need documentTypeByFileName to get the type of the C# object which the contents of the files will be mapped to. Each of these is just a wrapper for a list of a type which can be predicted by the name (e.g., ADocument's contents will be just a List). So, each of these Document types implements:

    interface DataListable {
        List<object> GetList();
    }

We need functionByFileName to handle each item from each of these lists.

But, as you can see there is a lot of repeating information here.

Is there a way I can reduce this to a single collection and then be able to manipulate the contents of the collection to avoid all this repetition?

I was thinking about possibily using an OrderedDictionary just to remove the List, but it seems that OrderedDictionary would not take parameterized types...





Printing a reflected hollow right triangle pattern (*) in Kotlin

I am currently taking a programming principles class with a Kotlin language focus at my school due to my growing interest in programming.

I am to create a program that takes user input for an integer. After I collect this information, I need to print two triangles in a asterisk (*) pattern (I had no problem completing these steps).

In addition, there is potential for extra credit which I am not working on more for experience than the extra points as I am looking good grade wise. I need to take the first triangle and reflect it while maintaining the properties. So far, I am unable to figure out how I would keep the triangle hollow and get the third side on to it.

My code:

fun main() {

    // Prompt user for the triangle's size
    print( "How big do you want your triangles? " )

    // Get the triangle's size from the user and store in a variable
    var triangleSize = readLine()!!.toInt()

    // Decrementor for internal spaces
    var decrementor = triangleSize

    // Incrementor for internal spaces
    var incrementor = 2

    // Case given a 0 is entered
    if ( triangleSize == 0 ) {

        // Case given 1 is entered
    } else if ( triangleSize == 1 ) {

        println( "*" )

        println( "1" )

        for ( i in 1..( triangleSize - 1 )) {

            print( " " )

        }

        print( "*" )

        // Case given number entered that is not 0 or 1
    } else {

        // Print the top point of the triangle
        println( "*" )

        // Print the sides of the triangle
        for ( i in 0..( triangleSize - 3 )) {

            print( "*" )

            for ( i in 1..( triangleSize - decrementor )) {

                print( " " )

            }

            println( "*" )

            decrementor--

        }

        // Print the bottom of the triangle
        for ( i in 1..triangleSize ) {

            print( "*" )

        }

        println()

        // Print the numbers triangle
        for ( i in 1..triangleSize ) {

            for ( j in 1..i ) {

                print( "$j" )

            }

            println()

        }

        // Print the top of the inverse triangle
        for ( i in 1..( triangleSize - 1 )) {

            print( " " )

        }

        println( "*" )

        for ( i in 1..( triangleSize - 2 )) {

            for ( i in 1..( triangleSize - incrementor )) {

                print( " " )

            }

            println( "*" )

            incrementor++

        }

        // Print the bottom of the inverse triangle
        for ( i in 1..triangleSize ) {

            print( "*" )

        }

    }

}




ClassNotFoundException while loading class from a java 9 module that was loaded at runtime

I'm getting a ClassNotFoundException when I'm trying to load a class using Class.forName() that was added to the JVM using a ModuleLayer.

This is the error message:

Exception in thread "main" dev.teamnight.nightweb.core.module.ModuleException: Module does not contain main class dev.teamnight.nightweb.Test.TestApp
        at dev.teamnight.nightweb.core/dev.teamnight.nightweb.core.module.JavaModuleLoader.loadModule(JavaModuleLoader.java:80)
        at dev.teamnight.nightweb.core/dev.teamnight.nightweb.core.module.ModuleManagerImpl.loadModule(ModuleManagerImpl.java:92)
        at dev.teamnight.nightweb.core/dev.teamnight.nightweb.core.module.ModuleManagerImpl.loadModules(ModuleManagerImpl.java:64)
        at dev.teamnight.nightweb.core/dev.teamnight.nightweb.core.impl.NightWebCoreImpl.<init>(NightWebCoreImpl.java:194)
        at dev.teamnight.nightweb.core/dev.teamnight.nightweb.core.Main.main(Main.java:21)
Caused by: java.lang.ClassNotFoundException: dev.teamnight.nightweb.Test.TestApp
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at java.base/jdk.internal.loader.Loader.loadClass(Loader.java:544)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:398)
        at dev.teamnight.nightweb.core/dev.teamnight.nightweb.core.module.JavaModuleLoader.loadModule(JavaModuleLoader.java:66)
        ... 4 more

I used the example from the ModuleLayer JavaDoc in order to load the class:

        ModuleMetaFile metaFile = this.getModuleMetaFile(path);

        ModuleFinder finder = ModuleFinder.of(path.toAbsolutePath());
        ModuleLayer parent = ModuleLayer.boot();
        Configuration conf = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of(metaFile.getModuleIdentifier()));
        ClassLoader scl = ClassLoader.getSystemClassLoader();
        ModuleLayer layer = parent.defineModulesWithOneLoader(conf, scl);

        try {
            ClassLoader loader = layer.findLoader(metaFile.getModuleIdentifier());
            Class<?> clazz = Class.forName(metaFile.getMainClass(), true, loader);

            try {
                NightModule module = (NightModule) clazz.getConstructor().newInstance();

                return module;
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                throw new ModuleException(e, "Missing public " + clazz.getSimpleName() + "() constructor in " + metaFile.getMainClass());
            }
        } catch (ClassNotFoundException e) {
            throw new ModuleException(e, "Module does not contain main class " + metaFile.getMainClass());
        }
    }

The Module is loaded into the ModuleLayer as I checked by checking layer.modules(), but it is throwing the Exception above.





Java count appearences of variable/method in the code

I want to find out how often one specific variable appears or how often one specific method is called in the code and use this number in the same code. For Example:

public static main(String[] args){
   int a = 0;
   System.out.println(mysticMethod());
   int a++;
   int a = 3;
}

The mysticMethod() should now count how often the variable a appears in this class or the main method. Is there any way to do so?

I am grateful for all answers!





java.lang.StringIndexOutOfBoundsException: String index out of range when package name is changed

I want to read the annotations from .class file placed into random folder. I tried this:

            public static void main(String[] args) throws Exception
            {    
                final File folder = new File("/opt/test");
                processAnnotatedFiles(listLocalFilesAndDirsAllLevels(folder));

            }

        public void processAnnotatedFiles(List<File> list) throws IOException, ClassNotFoundException {
            out.println("Directory files size " + list.size());

            for(int i=0; i<list.size(); i++) {
                out.println("File " + list.get(i).getName());

                File file = list.get(i);

                String path = file.getPath();

                String[] authors = getFixFromClassFile(Paths.get(path));
                System.out.println(Arrays.toString(authors));
            }

        }

        public List<File> listLocalFilesAndDirsAllLevels(File baseDir) {

            List<File>  collectedFilesAndDirs = new ArrayList<>();
            Deque<File> remainingDirs = new ArrayDeque<>();

            if(baseDir.exists()) {
                remainingDirs.add(baseDir);

                while(!remainingDirs.isEmpty()) {
                    File dir = remainingDirs.removeLast();
                    List<File> filesInDir = Arrays.asList(dir.listFiles());
                    for(File fileOrDir : filesInDir)  {
                        // We need to process only .class files
                        if(fileOrDir.getName().endsWith(".class")){
                            collectedFilesAndDirs.add(fileOrDir);
                            if(fileOrDir.isDirectory()) {
                                remainingDirs.add(fileOrDir);
                            }
                        }
                    }
                }
            }

            return collectedFilesAndDirs;
        }

        private String[] getFixFromClassFile(Path pathToClass) throws MalformedURLException, ClassNotFoundException {
            // Create class loader based on path
            URLClassLoader loader = new URLClassLoader(new URL[]{pathToClass.toUri().toURL()});

            // convert path to class with package
            String classWithPackage = getClassWithPackageFromPath(pathToClass);

            // Load class dynamically
            Class<?> clazz = loader.loadClass(classWithPackage);
            Fix fix = clazz.getAnnotation(Fix.class);
            if (fix == null) {
                return new String[0];
            }

            return fix.author();
        }

        private String getClassWithPackageFromPath(Path pathToClass) {
            final String packageStartsFrom = "com.";
            final String classFileExtension = ".class";
            final String pathWithDots = pathToClass.toString().replace(File.separator, ".");
            return pathWithDots.substring(pathWithDots.indexOf(packageStartsFrom)).replace(classFileExtension, "");
        }

I get java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1927)

In this part I want to create a package into random dir. It is really hard to create a valid package from path because there is no any rule package names should follow.

Can you give me some advice how this can be fixed?





Dictionary of generic functions with different type per entry

Is it possible to achieve having typed func in a dict, with different types as keys and no casting in the func.

Something like this:

class Program
{
    class Person
    {
        public int Id { get; set; }
    }

    class Dog
    {
        public string Name { get; set; }
    }

    static void Main(string[] args)
    {
        var funcDict = new Dictionary<Type, Func<object, object, bool>>()
        {
            {typeof(Person), (Person p1, Person p2) => p1.Id == p2.Id},
            {typeof(Dog), (Dog d1, Dog d2) => d1.Name == d2.Name},
        };

        var p1 = new Person()
        {
            Id = 4
        };

        var p2 = new Person();

        Console.WriteLine(funcDict[p1.GetType()].Invoke(p1, p2));
    }
}

Best I can come up with is creating the funcs with object types and then casting in the func body, but if possible would like to avoid that, cause it would make for a much cleaner API.

var funcDict = new Dictionary<Type, Func<object, object, bool>>()
{
    {typeof(Person), (o1, o2) => ((Person) o1).Id == ((Person) o2).Id},
};




Cannot get custom annotations from Java class

I want to get class level annotation from Java class:

    class FixAnnotation {

        public String[] author;

    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface Fix {

        public String[] author() default "";

    }

I tried this example of compiled java class:

@Component("test")
@Fix(
    author = {"Example author 1", "Example author 2"}
)
public class Order implements Action {
..
}

But when I try:

public List listLocalFilesAndDirsAllLevels(File baseDir) {

        List<File>  collectedFilesAndDirs = new ArrayList<>();
        Deque<File> remainingDirs = new ArrayDeque<>();

        if(baseDir.exists()) {
            remainingDirs.add(baseDir);

            while(!remainingDirs.isEmpty()) {
                File dir = remainingDirs.removeLast();
                List<File> filesInDir = Arrays.asList(dir.listFiles());
                for(File fileOrDir : filesInDir)  {
                    // We need to process only .class files
                    if(fileOrDir.getName().endsWith(".class")){
                        collectedFilesAndDirs.add(fileOrDir);
                        if(fileOrDir.isDirectory()) {
                            remainingDirs.add(fileOrDir);
                        }
                    }
                }
            }
        }

        return collectedFilesAndDirs;
    }

      List<File> list;

      for(int i=0; i<list.size(); i++) {
            File item = list.get(i);
            System.out.println(item.getName());

            Fix name = item.getClass().getAnnotation(Fix.class);

            out.println("author: " + name.author());
       }

I get NPE. Do you know how I can get the annotation content?





mardi 28 avril 2020

Calling a generic method using type variable [duplicate]

I am trying to call a generic method using classes that match an interface within the executing assembly and reflection. I'm stuck on how to pass the type as generic.

I end up with either one of two error messages:

a) By passing type directly: Type is a variable but is used like a type

or

b) By passing type.GetType(): Operator '<' cannot be applied to operands of type 'method group' and 'Type'

What I have so far:

public void LoadClasses()
{
    foreach (Type type in Assembly.GetExecutingAssembly().DefinedTypes)
        if (typeof(ISomeInterface).IsAssignableFrom(type))
            CallMethod<type>();
}

public void CallMethod<T>() where T : class, new()
{
    T instance = new T();
    ((ISomeInterface)instance).CallMethod();
}




C# Pass any method as parameter

I'm making a networking application and i'd like to be able to pass methods no matter the parameters so i can get them and store them in a dictionnary so that once a packet arrive i am able to read it using the parameters the same remote method used

I'd like something like this:

Register(Enum key, [method with unknown parameters])

I've looked everywhere for an answere but none fit my issue





Memory not free on Tomcat with my .war project for Search and Run Junit Test Method/Class

in my function i load jar for search in all class all Test Method (Annotation.Test or TestFactory). when i call this method memory not is free, infact with free -h in poll i view that when call this function memory increases and at end not released. I type: j.close(); and child.close(); for close JarFile and URLClassLoader.

public JarClassMethod getAllTests() {

    JarClassMethod testClassObjMap= new JarClassMethod(); //<-----  simple HashMap<String,HashMap<String, List<String>>>

    LoadLibrary loadLibrary=new LoadLibrary();
    List<JarFile> jarList= loadLibrary.getListJar(pathJars).stream().map(f -> {
        try {
            return new JarFile(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    })
        .collect(Collectors.toList());

    for (JarFile j : jarList) {
        URLClassLoader child = new URLClassLoader(
                new URL[] {new File(j.getName()).toURI().toURL()},
                this.getClass().getClassLoader()
        );

        for (Enumeration<JarEntry> entries = j.entries(); entries.hasMoreElements(); ) {
            JarEntry entry = entries.nextElement();
            String file = entry.getName();
            if (file.endsWith(".class")) {
                String classname = file.replaceAll("/", ".")
                        .substring(0, file.lastIndexOf("."));
                try {
                    Class<?> currentClass = Class.forName(classname,true,child);
                    List<String> testMethods = new ArrayList<>();
                    for (int i = 0; i < currentClass.getMethods().length; i++) {
                        Method method = currentClass.getMethods()[i];
                        Annotation annTest = method.getAnnotation(Test.class);
                        Annotation annTestFactory = method.getAnnotation(TestFactory.class);
                        if (annTest != null || annTestFactory != null) {
                            testMethods.add(method.getName());
                        }
                    }//fine for metodi
                    if (testMethods.size() >=1) {
                        //if windows: testClassObjMap.put(j.getName().substring(j.getName().lastIndexOf("\\")+1),classname,testMethods);
                        testClassObjMap.put(j.getName().substring(j.getName().lastIndexOf("/")+1),classname,testMethods);
                        System.out.format("%s %s %s",j.toString(),classname,testMethods);
                    }

                }catch (NoClassDefFoundError e) {
                    System.out.println("WARNING: failed NoClassDefFoundError " + classname + " from " + file);
                } 
                catch (Throwable e) {
                    System.out.println("WARNING: failed to instantiate " + classname + " from " + file);
                }

            }//if .class

        }//chiudo jarentry for
        j.close();
        child.close();
    }//chiudo jarfile for
    return testClassObjMap;
}


public class LoadLibrary {
    public List<File> getListJar(String path_jars) throws IOException {
        String[] extensions = new String[] { "jar" };
        List<File> jarFiles = (List<File>) FileUtils.listFiles(new File(path_jars), extensions, false);
        return jarFiles;
}

//method for runTest
public void runOne(String jar, String class_name, Optional<String> test_name, TestExecutionListener listener)  {
        Launcher launcher = LauncherFactory.create();

        ClassLoader loader = URLClassLoader.newInstance(
                new URL[] { new File(pathJars+"/"+jar).toURI().toURL() },
                getClass().getClassLoader()
            );

        loader.getClass();
        Class cls=Class.forName(class_name,true,loader);
        Constructor constructor = cls.getConstructor();
        constructor.newInstance();

        LauncherDiscoveryRequest request;
        if (test_name.isPresent()) {
            Method m = cls.getMethod(test_name.get());
            request = LauncherDiscoveryRequestBuilder.request()
                    .selectors(selectMethod(cls,m))
                    .build();
        }
        else{
            request = LauncherDiscoveryRequestBuilder.request()
                    .selectors(selectClass(cls))
                    .build();
        }

        TestPlan testPlan = launcher.discover(request);
        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);

    }

For you I close all? how free memory at end of each function RunOne and getAllTests()?

thanks Regards





How Microsoft Hides C# Internal Classes from a DLL's Metadata?

It all started when I wanted to analyze the code around CVE-2017-8759. I knew that the fix for the CVE was in a class named WsdlParser.cs inside System.Runtime.Remoting.dll which is part of the .Net Framework. You probably have this dll on your computer at a location similar to:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7\System.Runtime.Remoting.dll

I used ilspycmd to re-assemble the code back to C#, and noticed that the WsdlParser.cs was missing in the output directory:

enter image description here

I later used CFF Explorer and saw that this type is indeed missing in the metadata in TypeDefs:

enter image description here

However, I know for a fact that this class is there:

  • It's in Microsoft's documentation: https://referencesource.microsoft.com/System.Runtime.Remoting/metadata/wsdlparser.cs.html
  • When using reflection and LoadAssembly() I was able to find the class:

        Assembly assembly = Assembly.LoadFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7\System.Runtime.Remoting.dll");
    
        foreach (var type in assembly.GetTypes())
        {
            if (!type.FullName.EndsWith("WsdlParser"))
            {
                continue;
            }
    
            Console.WriteLine("Great Success");
        }
    

I noticed that this behavior is consistent to all internal classes in this dll, but I don't understand how it makes sense. My guess is there might be a post-build procedure to remove data of internal types, but if so, how was I able to find the class by loading the assembly? I thought that the CIL loads types using the TypeDef metadata, but is there an additional space where this data is stored?

In order to understand it better, I created a C# test project with an internal class, and inspected the metadata using CFF Explorer. The internal class was there, as it should be, in debug and in release builds.

So what is this voodoo?

Thanks guys.





Elegant way to parse json to C struct using latest C++ features

I'm using nlohmann json parse lib but i'm trying to make good use of the latest C++ extensions in order to make the parsing as generic and elegant as possible. Of course, some corner case specialization will be neded.

I've found visit_struct lib, but it uses boost.

Any suggestions ?





How to pass a reified parameter to some other function when current function can't be inline (but we have Reflections)?

Lets pretend we have an interface which defines the storage of data in some database by serializing them into json.

interface StorageApi {
    suspend fun store(key: String, value: Any)
    // inline suspend fun <reified T: Any> get(key: String): T // reification is not possible in interfaces since we can't inline them
    suspend fun <T: Any> get(key: String, kClass: KClass<T>): T // so I have to stick with some other way, like reflection.

}

And then we have an implementation of the method:

override suspend fun <T : Any> get(key: String, kClass: KClass<T>): T =
    Klaxon().parse<T>("") // obviously error by compiler since T goes through type-erasure

Here I cannot use T as it would go through Type-erasure at runtime. I have reflection but don't know how to use it in this purpose. The Klaxon.parse() function does not accept KClass for getting types.

Is there any way to bypass these or make some utility to use reflection in this purpose, or any other possible workarounds?





lundi 27 avril 2020

How do I get keys of an embedded struct using reflection? [duplicate]

I have a struct A

type A struct {
   KeyA string 
}

and I have another struct B

type B struct {
   A
   KeyB string
}

How do I access all the keys name Both KeyA and KeyB using only struct B with relection api . I have tried Get name of struct field using reflection but it only gives KeyB





How to cache class' instances in Groovy

I have the following method:

def <T> T getImpl(Class<T> category)
{
        def queryGetter

        if (DDLTool.isOracle())
        {
            queryGetter = // getting oracle implementation based on category (Portal|Portal365)
        }
        else if (DDLTool.isMSSQL())
        {
            queryGetter = // getting mssql implementation based on category (Portal|Portal365)
        }
        else if (DDLTool.isPostgres())
        {
            queryGetter = // getting postgres implementation based on category (Portal|Portal365)
        }

        return queryGetter
}

category can be the following:

  1. Portal.class
  2. Portal365.class

Hierarchy scheme:

Category -> Portal | Portal365 -> PostgresQueryGetterPortal/MssqlQueryGetterPortal/OracleQueryGetterPortal |  PostgresQueryGetterPortal356/MssqlQueryGetterPortal365/OracleQueryGetterPortal365

So, I need to get needed implementation based on category (Portal|Portal365). Also, I shouldn't use classpath everytime I call the method. A have to cache them somehow

How can I do that?

Thanks in advance





Generic (JComponent) event handling in Java?

I'm implementing a scripting language on top of the Java VM. Using reflection, I'm able to dynamically create Java helper objects, access their fields and invoke their methods. However, I have now hard-coded handling for specific event types. E.g.: JScrollBar addAdjustmentListener() using the Adjustable interface, JFrame windowClosing() using the WindowAdapter interface, JButton addActionListener using the ActionListener interface. On the event receiving end in the scripting language, an anonymous function is called with the event data, with 0, 1 or 2 parameters of arbitrary types. My question is: Is there a (reflective) way in Java to handle arbitrary events? Generically handling all JComponent subclass events would be a good start too.





Annotation with public visibilty constraint

I'm creating a CSV annotation.

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CsvAttribute {
     String columnName();
     int position();
}

I want to enforce that the annotation can only be placed on public members, either field or method. Is this possible? My brief research on this topic said no. My goal is to achieve this without the try-catch block. Since I have access to the object can I do this without reflection?

protected Map<Integer, String> convertFieldsToMap(){
    final Method[] m = this.getClass().getDeclaredMethods();
    return new ArrayList<>(Arrays.asList(m)).stream()
            .filter(p -> p.isAnnotationPresent(CsvAttribute.class))
            .collect(Collectors.toMap(
                    p -> p.getAnnotation(CsvAttribute.class).position(),
                    p -> this.invokeGetter(p)));
}

private String invokeGetter(Method m){
    try {
        return Objects.toString(m.invoke(this), "");
    } catch (IllegalAccessException | InvocationTargetException e) {
        LOG.error("@CsvAttribute annotation must be placed on public getters!");
        e.printStackTrace();
    }
    return StringUtils.EMPTY;
}




dimanche 26 avril 2020

In Java how to execute methods parallely while staying consistent using Java reflections?

Let's assume we have the following class:

public class Eval2 {
    Integer sumCount = 0;
    Integer mulCount = 0;
    public Integer sum(Integer a, Integer b) { sumCount++; return a + b; } 
    public Integer mul(Integer a, Integer b) { mulCount++; return a * b; } 
    public Integer results() {
        System.out.println("sums: " + sumCount + ", muls: " + mulCount);
        return 0;
    }
}

I have a list of type List<Pair<String, List<Integer>>, which contains which methods to execute, and the parameters, for example:

sum, [1, 2]
mul, [3, 4]
mul, [7, 9]
results, []

After I iterate through the list, and execute the methods using Java reflections, I get the following result, which is right:

3
12
63
sums: 1, muls: 2
0

But what if I want to execute these methods parallelly, while keeping it consistent? I made every method in Eval2 synchronized, and I did something like this in every iteration:

Thread t = new Thread() {
    public void run() {
        result[0] = (Integer) executedMethod.invoke(null, (Object[]) finalParametersArray);
        System.out.println(result[0]);
    };
t.start();

But, in this case, I can get the following result:

3
12
sums: 1, muls: 1
0
63

Which does not seem like it is consistent.

Finally, if I put t.join() after every t.start(), then it produces the right result, but then I guess it is not parallell, because every thread I make through the iterations does not start until the preceding thread executes. Thanks in advance.





Interface to have dynamic method names

Let's say an interface is exposed like this:

public interface IAction {
  void run();
  void walk();
  void stop();
  void jump();
}

Now like this there can be any number of actions. And each action is associated with an enum type as below:

public enum Action {
  RUN("run"),
  WALK("walk"),
  STOP("stop"),
  JUMP("jump")
}

Now every time I want to add more actions then I need to add an enum and also associated method in IAction interface.

Instead, Can the interface methods be exposed from the enum anyhow? And any implementation of the IAction interface should always be dependent on enum Action. And all those enum types in Action should be exposed. Is this possible?





Protobuf Java Reflection

I'm trying to deserialize protobuf messages via reflection. Specifically I'm trying to send events over a queue but that does not really affect the problem. Here is the situation:

  • Service A has .proto file with definitions. Using a maven plugin I generated the code for this messages. When a message instance is serialized I write over the wire the length of the byte[], the descriptor full name and the data itself. This works flawlessly.
  • Service B has the same version of the .proto file and has the same classes autogenerated. When I receive the message I lookup for the type Descriptor using the protobuf FileDescriptor. Here is my problem, I cannot really build an instance of type T using its descriptor. Not even a instance of Object which could be later downcasted.

I could use DynamicMessage.parseFrom but that's not a real solution as I could not downcast later. I've been researching and looks like the way to go is using Message.getDefaultInstance and later call newBuilderForType.mergeFrom(byte []). But there is no way to programatically access to all the default instances given a FileDescriptor so any user should list all the messages available on a given descriptor and invoke the defaultInstance method. Other option is to send the full package name over the wire and rely on Class.forName to locate the class and the invoke getDefaultInstance but this is not very safe.

My question is: Is there an easier way of building generic instances of protobuf classes or I have missed something?

Note: The signature of the event handler would look like public void onT( T event ); that's why the downcast is important rather than relying on DynamicMessage





How to assert that collection is IReadOnlyCollection using NUnit

I have a method in SomeClass, which return IReadOnlyCollection. Something like that:

    public calss SomeClass
{
   private readonly List<Part> _parts;

   ...

   public IReadOnlyCollection<Part> GetAllParts =>
            this._parts;
}

In my Unit tests I want to assert that returned collection (expectedCollection) is IReadOnlyCollection. I have tried with reflection:

[Test]
        public void TestWariorsShoudReturnReadOnlyCollectionOfWariors()
        {
            var expectedCollection = MyPartsLib.GetAllParts;

            Type type = expectedCollection.GetType();
            string acctualtypeName = type.Name;
            string expectedTypeName = "IReadOnlyCollection";
            Assert.AreEqual(expectedTypeName,acctualtypeName);
        }

But acctualtypeName after executing is List`1. How can I assert that expectedCollection is IReadOnlyCollection?

Thanks for you help.





samedi 25 avril 2020

How to define a class-level macro in a module in Ruby?

In the Ruby programming language, I am creating a class with a class-level macro, as follows:

class Timer 
  def self.add_time
    def time
      STDERR.puts Time.now.strftime("%H:%M:%S")      
    end 
  end 
end 

The class method add_time, when executed, will generate a time method. Now, I can execute that class-level macro in another class Example as follows:

class Example < Timer 
  add_time 
end 

When I now call time on an instance of class Example, the time method is present there, as I intended:

ex = Example.new 
ex.time

and prints the current time: 23:18:38.

But now I would like to put the add_time macro in a module and still have the same overall effect. I tried with an include like this:

module Timer 
  def self.add_time
    def time
      STDERR.puts Time.now.strftime("%H:%M:%S")      
    end 
  end 
end 

class Example 
  include Timer
  add_time
end 

ex = Example.new 
ex.time

but then I receive an error that the method add_time is not defined on the class Example: NameError: undefined local variable or method ‘add_time’ for Example:Class. So then I tried with an extend instead like this:

class Example 
  extend Timer
  add_time
end

but it gives me a similar error.

So the question is: How can I get the same effect as in my original example where the Timer was defined as a class, but using a module instead?





Reflection in javaFX application

I am supposed to write a window application using the JavaFX library that uses the reflection mechanism will automatically detect, edit and change object properties of any class written in the convention JavaBean. Properties are private fields of an object, to which access is controlled by so-called access methods. getters and setters. Unfortunately Java is not my strongest element so I am asking for some help with this task. The application itself should look something like this:

https://imgur.com/a/oDQ3Mab

Currently, when I try to save a change in the fields but it keeps popping up that I haven't saved from "catch (Throwable e)".

Code:

1) Controller:

public class Controller {
@FXML
private TextField tekstField;
@FXML
private TextArea area_text;
@FXML
private VBox vbox;

private Class<?> MyClass;
private Object ObjectInstance;
LinkedList<sample.Field> fields = new LinkedList<>();

public void CreateObject() {
    vbox.getChildren().clear();
    this.fields.clear();
    try {
        MyClass = Class.forName(tekstField.getText());

        Field[] allFields = MyClass.getDeclaredFields();
        for (Field field : allFields) {
            field.setAccessible(true);
            String methodSetName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
            String methodGetName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
            Class[] setterArgs = new Class[1];
            setterArgs[0] = field.getType();
            Method setterMethod = MyClass.getMethod(methodSetName, setterArgs);
            Method getterMethod = this.MyClass.getMethod( methodGetName , null);
            String s = field.getName();
            HBox hb = new HBox();
            TextField textfield = new TextField();
            this.fields.add( new sample.Field(methodGetName, methodSetName, textfield, setterMethod, getterMethod, field.getType().getName()) );
            textfield.setPrefWidth(300);
            Label label = new Label("<- " + field.getName());
            label.setWrapText(true);
            hb.getChildren().add(textfield);
            hb.getChildren().add(label);
            vbox.getChildren().add(hb);

        }

        area_text.setText("Obiekt o nazwie: " + MyClass.getSimpleName() + " został utworzony!");
    } catch (ClassNotFoundException e) {
        area_text.setText("Błąd");
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}


public void SaveChanges() {
    String wiadomosc="";
    for (sample.Field field : fields) {
        Object[] args = new Object[1];
        try {
            switch( field.getFieldType() ) {
                case "int":
                    args[0] = Integer.parseInt(field.getTextField().getText());

                    break;
                case "java.lang.String":
                    args[0] = field.getTextField().getText();

                    break;
            }
        }
        catch(Exception e) {
            area_text.setText("Zła wartość");
        }
        try {
            field.getSetterMethod().invoke(ObjectInstance, args );
            wiadomosc = wiadomosc + "Wprowadzono: "+ field.getTextField().getText() +"\n";
            area_text.setText(wiadomosc);
        }catch(Throwable e) {
            area_text.setText("Nieudana próba zapisu!");
        }
    }
}

2) Book Class:

public class Book {
private String title;
private String autor;
private String type;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getAutor() {
    return autor;
}

public void setAutor(String autor) {
    this.autor = autor;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

}

3) Field Class:

public class Field {

private String getterName, setterName, fieldType;
private TextField textField;
private Method setterMethod, getterMethod;

public Field(String getterName, String setterName, TextField textField, Method setterMethod, Method getterMethod, String fieldType ) {
    this.getterName = getterName;
    this.setterName = setterName;
    this.textField = textField;
    this.setterMethod = setterMethod;
    this.getterMethod = getterMethod;
    this.fieldType = fieldType;
}

public String GetGetterName() {
    return this.getterName;
}
public String GetSetterName() {
    return this.setterName;
}
public TextField getTextField() {
    return this.textField;
}
public Method getSetterMethod() {
    return this.setterMethod;
}
public Method getGetterMethod() {
    return this.getterMethod;
}
public String getFieldType() {
    return this.fieldType;
}

}

I probably broke something before and I don't know where - I'm sorry about the spaggetti code in general.





What is the best method to make an object look wet in openGL?

enter image description here

What is the best method to make an object look wet in openGL ? And also what is the best way to implement puddles. Should I use cube map reflections for them ? I want to achive a similar look to this picture.





vendredi 24 avril 2020

kotlin.time.Duration and java reflection

It seems I've encountered a weird problem with interaction of java reflection API (particularly, java.lang.reflect.Proxy and kotlin.time.Duration. It looks like Java Reflection fails to determine method return type for kotlin.time.Duration. Consider the following example:

@file:JvmName("Main")
package org.test.kotlin.time.duration

import java.lang.reflect.Proxy
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
import kotlin.time.seconds

@ExperimentalTime
interface I {
    fun getNullableDuration(): Duration? = 1.seconds
    fun getRange(): IntRange = 1..3
    fun getDuration(): Duration = 1.seconds
}

class IC: I

inline fun <reified T> T.sampleProxy(): T = sampleProxy(T::class.java)

fun <T> sampleProxy(c: Class<T>): T {
    return c.cast(Proxy.newProxyInstance(c.classLoader, arrayOf(c)) { _, method, _ ->
        println("[proxy] ${method.declaringClass.name}::${method.name} return type is ${method.returnType}")
        when (method.name) {
            "getNullableDuration", "getDuration" -> 1.seconds
            "getRange"                           -> 0..1
            else                                 -> TODO("method ${method.name} isn't handled yet")
        }
    })
}

fun main() {
    val v: I = IC()
    println("I::getNullableDuration() return type is ${v::getNullableDuration.returnType}")
    v.sampleProxy().getNullableDuration()
    println("I::getRange() return type is ${v::getRange.returnType}")
    v.sampleProxy().getRange()
    println("I::getDuration() return type is ${v::getDuration.returnType}")
    v.sampleProxy().getDuration()
}

This code produces the following output:

I::getNullableDuration() return type is kotlin.time.Duration?
[proxy] org.test.kotlin.time.duration.I::getNullableDuration return type is class kotlin.time.Duration
I::getRange() return type is kotlin.ranges.IntRange
[proxy] org.test.kotlin.time.duration.I::getRange return type is class kotlin.ranges.IntRange
I::getDuration() return type is kotlin.time.Duration
[proxy] org.test.kotlin.time.duration.I::getDuration return type is double
Exception in thread "main" java.lang.ClassCastException: class kotlin.time.Duration cannot be cast to class java.lang.Double (kotlin.time.Duration is in unnamed module of loader 'app'; java.lang.Double is in module java.base of loader 'bootstrap')
    at com.sun.proxy.$Proxy2.getDuration(Unknown Source)
    at org.test.kotlin.time.duration.Main.main(main.kt:38)
    at org.test.kotlin.time.duration.Main.main(main.kt)

Process finished with exit code 1

As one can see, inside sampleProxy return types for getNullableDuration() and getRange() are determined correctly (kotlin.time.Duration? expectedly becomes kotlin.time.Duration), while getDuration() suddenly becomes a method returning double and the cast from kotlin.time.Duration to double on return from the method fails with the exception.

What could be a reason for the problem? How can I workaround it?

My environment:

  • OpenJDK 11.0.6+10
  • Kotlin 1.3.71
  • Linux/x86-64




Access list of methods by the generic type parameter T without any instance of the class

private Map<String, Service> serviceMap = new HashMap();

public <T extends Service> T getService() {
    return (T) this.serviceMap.get(T.class.getTypeName()); // <-- is not possible
}

I want to access the definition of a class using reflection without having any instance of that class by just using T, but it is not possible with T.class, so I ask if there is any other solution with up to Java 14 to get access without passing a Class<T> as parameter to getService(). You see in the code what I'm trying to achieve.





Get event Action using Reflection in Blazor

I have following service:

public class Service
{

    private List<Model> _modelList = new List<Model>();

    public List<Model> Modellist
    {
        get { return _modelList ; }
        private set
        {
            _modelList = value;
            NotifyStateChanged();
        }
    }

    public event Action OnChange;
    public void NotifyStateChanged() => OnChange?.Invoke();
}

and normally used like:

protected override void OnInitialized()
{
    _Service.OnChange += StateHasChanged;
}

But i want to make that generic, and get the event using reflection. I tried the following with no luck:

protected override void OnInitialized()
{
    var backingField = Service.GetType().GetField("OnChange", BindingFlags.Instance | BindingFlags.NonPublic);
    var delegateInstance = (Action)backingField.GetValue(Service);
    delegateInstance += StateHasChanged;
}

How do I get this working?

Many Thanks!





.NET, C#, reflection GetMethod return null (trying to get Methods inside third party dll)

I am trying to create an instance and call a method inside the DLL, but for some reason GetMethod returns null. Can anyone please advise what is wrong here?

//this works fine
Type myDllType = Type.GetTypeFromProgID("Application.name");

//this works fine too
object dllInstance = Activator.CreateInstance(myDllType);

//this returns null,  I am 100% sure "methodmd" exists
MethodInfo methodCommand = myDllType.GetMethod("methodmd");




Using Reflection inside stream intermediate operations in Java

public class A {
    private List<B> listOfB = new LinkedList<>();
    //getter setters
}


public class B {
        private BigDecimal fieldOne;
        //8 more BigDecimal fields like this...
        private BigDecimal fieldTen;
        //getter setters
    }

I have a list of A objects and there I aimed to get sum of each fields of B objects to show it on a JSF page.

At first I thought to write ten methods like getSumOfFieldOne() ... getSumOfFieldTen() etc. in Class A. Then I thought maybe there could be a shorter way to do it.

I tried to use Reflection:

  public BigDecimal getSumOfField(String fieldName) throws Exception {
        Method getter = A.class.getMethod(String.format("get%s", StringUtils.capitalize(fieldName)));
        return getListOfB().stream()
               .map((BigDecimal)getter.invoke(A.class))
               .reduce(BigDecimal.ZERO, (d1, d2) -> d1.add(d2));
    }

and on JSF Page:

 <h:outputText value="#{theController.listOfA.getSumOfField('fieldOne')}"/>
  ...
 <h:outputText value="#{theController.listOfA.getSumOfField('fieldTen')}"/>

But it was not successful at compile time due to .map((BigDecimal)getter.invoke(A.class)) in getSumOfField

Writing 10 methods for each field or collecting the sum of these fields in a map in Class A are another options which I normally use in other cases. But I would like to try reflection way as it is more interesting and challenging. Could you please help me?

Thanks in advance.





Java extract generic type parameters with reflection from interface

I'm writing a custom Java annotation for processing CrudRepositories with Reflection in Java Spring. With the org.reflections.reflections library. I'm getting all interfaces annotated with my annotation as a class file like so:

Reflections reflections = new Reflections("basePackage");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(MyAnnotation.class);

Only interfaces, which at some point extend JpaRepository are annotated with my @MyAnnotation at the class level.


My repository structure is as follows: There are two cases,

first case:
public interface SomeRepo extends JpaRepository<SomeEntity, Long> {...}

the second case is composed out of a inheritance hierarchy:
public interface SuperClassRepo <T extends SomeRandomEntity> extends JpaRepository<T, String> {...}
public interface SubClassRepo extends SuperClassRepo<SubEntityOfSomeRandomEntity> {...}

My goal is now to extract the generic type parameters of the underlying JpaRepository. I achieved to do that if the annotated class is a Java class, not an interface. How can I achieve the same for an interface? I guess I'm also having trouble because of the inheritance. I guess I have to get the "super class" until I reach the JpaRepository and then somewhat extract the generic type arguments.

Help is very much appreciated, thanks in advance





Invoke a method with reflection

I would like to create a method that takes an unspecified object as an argument and uses its methods.

using System;
using System.Reflection;

namespace TestReflection
{
    class Program
    {
        static void Main(string[]args)
        {
            Test t1 = new Test
            {
                A = 2,
                B = "test"
            };

            Program p = new Program();
            Console.WriteLine("\nNormal");
            Console.WriteLine("A: {0}", t1.A);
            Console.WriteLine("B: {0}", t1.B);
            Console.WriteLine("MethodWithoutArguments: {0}", t1.MethodWithoutArguments());
            Console.WriteLine("MethodWithArguments: {0}", t1.MethodWithArguments(5));

            p.Reflection(t1);
        }
        private void Reflection<T>(T item)
        {
            Type t = item.GetType();
            object classInstance = Activator.CreateInstance(t, null);
            Console.WriteLine("\nReflection");
            foreach (PropertyInfo propertyInfo in t.GetProperties())
            {
                object value = propertyInfo.GetValue(item, null);

                Console.WriteLine("{0} = {1}", propertyInfo.Name, value);
            }

            var temp = t.GetMethod("MethodWithoutArguments").Invoke(classInstance, null);
            Console.WriteLine("MethodWithoutArguments: {0}", temp);

            temp = t.GetMethod("MethodWithArguments").Invoke(classInstance, new object[] { 5 });
            Console.WriteLine("MethodWithArguments: {0}", temp);
        }
    }

    public class Test{
        public int A { get; set; }
        public string B { get; set; }
        public string MethodWithoutArguments()
        {
            return A + " " + B;
        }

        public string MethodWithArguments(int i)
        {
            return A + " " + i;
        }
    }
}

Output

  1. Normal

    • A: 2
    • B: test
    • MethodWithoutArguments: 2 test
    • MethodWithArguments: 2 5
  2. Reflection

    • A = 2
    • B = test
    • MethodWithoutArguments: 0 // incorrect
    • MethodWithArguments: 0 5 // incorrect

With the reflaction method I get correctly the Parametries but if I call a method, the result is wrong, what am I doing wrong?





How to call main method on class identified by String

I'm trying to call the main method on a Java class identified by a String. In the actual program, the class identifier will be a variable, but for the moment I'm trying this:

try {       
    Class c = Class.forName("Arena");

    Class[] aarg = new Class[1];  
    aarg[0] = String[].class;

    Method m = c.getMethod("main", aarg); // Needs parameter class list
    m.invoke(newargs);
}           
catch (Exception e) {
    System.err.println(e);      
}

First, I get a compiler warning (Athena is the name of the class I'm currently working in):

Note: Athena.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Then on testing I get this exception:

java.lang.IllegalArgumentException: wrong number of arguments

I feel like the primary thing is I don't know how to identify the parameter of main() as an array of the String class (failed to find an example of that), but maybe I'm missing more than that.





Jackson's `Visibility.Any` performance

Using Jackson with Lombok's @Accessors(fluent=true) requires to add @JsonAutoDetect(Visibility.Any) annotation:

@Data
@NoArgsConstructor
@Accessors(fluent=true)
public class Pojo{
  private String fieldOne;
  private String fieldTwo;
}

I am curious of the performance of Visibilty.Any. Does it use reflection or compile time hooks are added?





jeudi 23 avril 2020

Generic return type in Scala structural type method

I'm trying to create a structural type in Scala with a method that has a generic return type. For instance, something like:

type Manipulable[T] = Any {
  def +(x: Int): T
}

def add[T <: Manipulable[T]](o: T, x: Int) = o + x

// these lines throw Exceptions
add(19.0, 3)
add(3, 3)
add(42L, 3)

Scala's structural types are set scoped to AnyRef by default, so to use the value types (Java's primitives), we prepend the Any before the type definition. Structural types can take type parameters, as seen above, but those type parameters cannot then be used as the types of any method value parameters. (You could have x: => T, but not x: T.)

When trying to use add() on a Manipulable[Double] or Manipulable[Int] (etc.), though, we get a Java NoSuchMethodException. Note that this only happens with methods with purely generic return types. The following structural type, for instance, works fine:

type Manipulable[T] = Any {
  def getClass (): Class[T] // Class[_] also works
  def toString() : String
}

def gc[T <: Manipulable[T]](o: T): Class[T] = o.getClass()

gc(19.0) // Class[Double] = class java.lang.Double
gc(3)    // Class[Int] = class java.lang.Integer
gc(42L)  // Class[Long] = class java.lang.Long

def str[T <: Manipulable[T]](o: T): String = o.toString()

str(19.0) // String = 19.0
str(3)    // String = 3
str(42L)  // String = 42

I'm guessing this is an issue with value types in Scala, because reference types seem fine:

type Manipulable[T] = Any {
  def substring(x: Int) : T
}

def ss[T <: Manipulable[T]](o: T, x: Int) = o.substring(x)

ss("hello, world", 7) // prints "world"

Any ideas?





Getting the name of a static member property in Kotlin

I have a javaclass like this, inside of a Kotlin project:

public final class BuildConfig {
  public static final String FOO = "HelloWorld";
  public static final String ALT_FOO = "HelloWorldAlt";
}

How can I get a String with the value FOO? (not the value of the field, the name of the field)

i.e. val theName = "FOO"

For example later on I will have a map.

val map = mapOf("FOO" to "HelloWorldAlt", "BAR" to "CoronaGotMeInside")

and I want to do the below:

val result = map[theName]
println(result)
// HelloWorldAlt

I know I can get all the field values like the below, but I can't figure how to get the static member variable name off of a single static var. I don't want to iterate all staticProperties. I want to explicitly look one up.

val notResult = BuildConfig::class.staticProperties.filter { it.name == "FOO" }[0].getter.call()
println(notResult)
// HelloWorld

As an example of a not iterative solution, I want something like this:

val theName = BuildConfig.FOO::variableName() // Totally made up, but I want to act on the singular constant, not on a collection 

This would allow me to have some compile time confidence when using the variables name a map key. Crazy I know.





Correlate Java field type and generic parameter

Consider the following classes:

class A {
    B<Integer> b;
}

class B<T> {
    T t;
}

I need to write the follwing method:

Object create(Class clazz) {
    // todo
}

such that when create(A.class) is called, the returned value is an instance of A which contains an Integer in b.t. Naturally the method must not have any knowledge about A besides its class.

It is well known how to find out that the type of b in A is B<Integer>.

I am looking for a way to find out that the field t in B is intended to have the type of the first type parameter of B.





Stream through methods to find Rest mapping information

I have a simple, but incredibly ugly looking method. The issue I am having is that I feel this can be done a million times more elegantly. In addition, I would also like to scan a method for more than one annotation, and not just the Rest endpoint declarations.

I feel this can be done through a stream of Annotations[] (method.getDeclaredAnnotations()) and filtered by a List<Annotation> restEndpointAnnotationsAndOtherAnnotations, but I cannot seem to get it to work.

Any help would be greatly appreciated. I think it's probably a fairly fun challenge for some people. The primary issue I am getting (I think) is trying to convert Class<? extends Annotation> to Annotation, but perhaps I am missing the mark.

public RestEndpoint mapToRestEndpoint(Method method) {

        String url = null;

        if (method.isAnnotationPresent(GetMapping.class)) {
            url = method.getAnnotation(GetMapping.class).value()[0];
        } else
        if (method.isAnnotationPresent(PutMapping.class)) {
            url = method.getAnnotation(PutMapping.class).value()[0];
        } else
        if (method.isAnnotationPresent(PostMapping.class)) {
            url = method.getAnnotation(PostMapping.class).value()[0];
        } else
        if (method.isAnnotationPresent(PatchMapping.class)) {
            url = method.getAnnotation(PatchMapping.class).value()[0];
        } else
        if (method.isAnnotationPresent(DeleteMapping.class)) {
            url = method.getAnnotation(DeleteMapping.class).value()[0];
        } else
        if (method.isAnnotationPresent(RequestMapping.class)) {
            url = method.getAnnotation(RequestMapping.class).value()[0];
        } else return null;

        return new RestEndpoint(url, true);
    }

Where RestEndpoint is a simple POJO

@Value
public class RestEndpoint {

    @NonNull String endpoint;
    boolean isPublic;
}

Just to add: I can actually find where it matches the Rest mapping using streams, but I cannot then apply the .value() method to it (since it doesn't know what annotation it is, and would be just as tedious to then cast to multiple annotation types)





mercredi 22 avril 2020

.Net reflection to get nested property with custom attribute

I want to know the best way to get the prop info and value using reflection for a nested class by its custom attribute name. With below code I can get the prop info via recursion. But is there a better way or using LINQ. Note that I do not want to hard code the class type as similar to other solution

I also want to get the property value by custom attribute

e.g var propValue = ?????

 public class PlanetRoot

    {

        public void GetNeighborMoon()

        {

            Planet planet = new Planet();

            Product product = new Product();

            Neighbor neighbor = new Neighbor();

            neighbor.Moons = 10;

            neighbor.RingColor = "Red";

            product.Neighbors = new List<Neighbor>();

            product.Neighbors.Add(neighbor);

            planet.Product = product;



            //1. Get the RingColor property info of neighbor with attribute MyDBField(Name = "NeighborRing") . Is there a better way

            PropertyInfo propInfo = DoRecursiveGetProperty(planet.GetType(), "NeighborRing");



            //2. Get the RingColor property value of neighbor with attribute MyDBField(Name = "NeighborRing")

            //var propValue = GetPropertyValue(????);

        }

    }



    private static PropertyInfo DoRecursiveGetProperty(Type type, string attribName)

    {

        PropertyInfo[] pi = type.GetProperties();

        PropertyInfo returnvalue = null;

        foreach (PropertyInfo p in pi)

        {

            var dbFieldAttribute = (MyDBFieldAttribute)Attribute.GetCustomAttribute(p, typeof(MyDBFieldAttribute));

            if (dbFieldAttribute != null && attribName.ToUpper() == dbFieldAttribute.Name.ToUpper())

            {

                returnvalue = p;

                //Console.WriteLine(p.Name + " : " + (dbFieldAttribute != null && dbFieldAttribute.Name != null ? dbFieldAttribute.Name : "****"));

                break;

            }



            if (p.PropertyType.IsClass && !p.PropertyType.IsValueType && !p.PropertyType.IsPrimitive

            && p.PropertyType.FullName != "System.String")

                DoRecursiveGetProperty(p.PropertyType, attribName);



        }



        return returnvalue;



    }

    public class Planet

    {

        public string PlanetId { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public Product Product { get; set; }



        [MyDBField(Name="PubDate")]

        public string Publishdate { get; set; }



    }



    public class Product

    {

        public string ProductId { get; set; }

        public List<Neighbor> Neighbors { get; set; }



    }



    public class Neighbor

    {

        [MyDBField(Name = "NeighborRing")]

        public string RingColor { get; set; }

        public int Moons { get; set; }

    }



    public class MyDBFieldAttribute : System.Attribute

    {

        public string Name { get; set; }

    }




Instantiating a Case Class from a Large Parameter List

Guys I'm in trouble when I have a large parameter list, but when I have a few work perfectly, does anyone have any idea what it might be?

Small parameter list, Ok

scala> case class Foo(a: Int, b: String, c: Double)
defined class Foo

scala> val params = Foo(1, "bar", 3.14).productIterator.toList
params: List[Any] = List(1, bar, 3.14)

scala> Foo.getClass.getMethods.find(x => x.getName == "apply" && x.isBridge).get.invoke(Foo, params map (_.asInstanceOf[AnyRef]): _*).asInstanceOf[Foo]
res0: Foo = Foo(1,bar,3.14)

scala> Foo(1, "bar", 3.14) == res0
res1: Boolean = true

when I have a very large list of parameters, it displays the following error below:

scala> case class Foo(a1: String,a2: String,a3: String,a4: String,a5: String,a6: String,a7: String,a8: String,a9: String,a10: String,a12: String,a13: String,a14: String,a15: String,a16: String,a17: String,a18: String,a19: String,a20: String,a21: String,a22: String,a23: String,a24: String)
defined class Foo

scala> val params2 = Foo("bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar","bar").productIterator.toList  
params2: List[Any] = List(bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar, bar)

scala> val test = Foo.getClass.getMethods.find(x => x.getName == "apply" && x.isBridge).get.invoke(Foo, params2 map (_.asInstanceOf[AnyRef]): _*).asInstanceOf[Foo]
java.util.NoSuchElementException: None.get
  at scala.None$.get(Option.scala:347)
  at scala.None$.get(Option.scala:345)
  ... 46 elided




Does java spring caching break reflection?

I'm using spring boot and integrated caching recently. Within my tests I use reflection a bit.

Here is an example:

@Service
public class MyService {

    private boolean fieldOfMyService = false;

    public void printFieldOfMyService() {
        System.out.println("fieldOfMyService:" + fieldOfMyService);
    }

    @Cacheable("noOpMethod")
    public void noOpMethod() {
    }

}

And this is the test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MyApplication.class })
public class MyServiceTest {

    @Autowired
    private MyService myService;

    @Test
    public void test() throws Exception {

        myService.printFieldOfMyService();

        boolean fieldOfMyService = (boolean) FieldUtils.readField(myService, "fieldOfMyService", true);

        System.out.println("fieldOfMyService via reflection before change:" + fieldOfMyService);

        FieldUtils.writeField(myService, "fieldOfMyService", true, true);

        boolean fieldOfMyServiceAfter = (boolean) FieldUtils.readField(myService, "fieldOfMyService", true);

        System.out.println("fieldOfMyService via reflection after change:" + fieldOfMyServiceAfter);

        myService.printFieldOfMyService();

    }

}

As you can see it's quite simple:

  • MyService has a private field fieldOfMyService
  • the test changes this from false to true via reflection

problem

  • everything works fine without caching.. this is the output:
fieldOfMyService:false
fieldOfMyService via reflection before change:false
fieldOfMyService via reflection after change:true
fieldOfMyService:true

Now I activate caching via:

  • @EnableCaching in spring
  • and then you get this:
fieldOfMyService:false
fieldOfMyService via reflection before change:false
fieldOfMyService via reflection after change:true
fieldOfMyService:false                      <<<<< !!!

Long story short:

  • when caching gets activated the service seems to be immune against changes made via reflection

The funny thing is, this only happens when the according service actually uses caching via at least one @Caching annotated method. In case the service does not have this like:

@Service
public class MyService {

    private boolean fieldOfMyService = false;

    public void printFieldOfMyService() {
        System.out.println("fieldOfMyService:" + fieldOfMyService);
    }

}

.. then it still works.

I guess this has something to do with the layers which get added when caching is activated. But... why? And is there a solution to it?

Thanks in advance for your help :-)





Pass dynamic Type to Generic List

Basically I want to pass Type which is calculated on run time to List< T>:

Type someType = GetSomeType()
List<someType> myList = new List<someType>();

Is that possible?





Passing Type variable as a type of generic method [duplicate]

I have a dictionnary that represent a association between a value type enum and a type domain entity.

        Dictionary<SettingType, Type> dictionnary = new Dictionary<SettingType, Type>() {
            {SettingType.GameBoard, typeof(GameBoardParameterLine)},
            {SettingType.Mountain, typeof(MountainParameterLine)},
            {SettingType.Treasure, typeof(TreasureParameterLine)},
            {SettingType.Adventurer, typeof(AdventurerParameterLine)}
        };

I have this following generic method that works fine:

        public static IEnumerable<T> CreateGroupOf<T>(IEnumerable<IEnumerable<string>> rawDataGroup) where T : ParameterLine
    {
        return rawDataGroup.Select(rawSettings => (T)Activator.CreateInstance(typeof(T), rawSettings));
    }

I want to call this static method by passing a variable of type "Type" retrieve from dictionnary :

            Type currentType = dictionnary.GetValueOrDefault(SettingType.GameBoard);
        IEnumerable<GameBoardParameterLine> parameterLineGroup = ParameterLineGroupFactory.CreateGroupOf<currentType>(data);

The problem is that i got cannot implicity convert exception.

I read this Using System.Type to call a generic method but that doesn't resolve a problem for me beacause of the return type that is "Object".





How to get all child properties name from EDM model/Class

Here is the class

    public class AmountData
        {
            public int Id{ get; set; }
            public decimal Amount { get; set; }
            public SentAmount SentAmount{ get; set; }
        }

    public class SentAmount
      {
        public decimal SentAmount { get; set; }
      }

    public class CreditAmount
    {
        public int Id { get; set; }

        public string Timestamp { get; set; }

        public DateTime ReceivedTime { get; set; };

        public byte[] RowVersion { get; set; }

        public bool IsActive { get; set; }

        public AmountData Credit { get; set; }

        public AmountData Debit { get; set; }

        public DateTime CreatedDate { get; set; }

        }

I want all the properties name, type from CreditAmount, AmountData, SentAmount both but I can only use parent class (CreditAmount) for this.

I have tried this using recurisive method but fails

private List<Type> allTypes = new List<Type>();
public void GetProperties(Type type)
        {
            foreach (var p in type.GetProperties())
            {
                allTypes.Add(p.PropertyType);

                foreach(var q in p.PropertyType.GetProperties())
                {
                    GetProperties(q.PropertyType);
                }
            }
        }




mardi 21 avril 2020

Paramerized Constructor creation in Java at Runtime using Reflection API in Java

I have requirement where I need to create a parameterized constructor at Runtime may be with Reflections api it is possible but don't know how to. On reading the parameters at runtime i need to initialize values in the constructor of my model. Can anybody please help me on this.





Scala Reflection to generate a companion object and call the apply method

Here is the problem.

trait TestTrait[T, R] extends (T => R) 

// Class implementing TestTrait. This is one class, there are a number of class implementing TestTrait
class TestClass(val input: Map[String, String])extends ConfigurableDomainExtractor[String, String] {
  override def apply(value: String): String = ???
}

// Companion Object
object TestClass {
 def apply(properties: Map[String, String]): TestClass = TestClass(properties)
}

what I want to do is to define a method in util class lets say

class CreateInstance {
  def getInstance(fullyQualifiedClassName: String, properties: Map[String, String]): TestTrait = ???

// fullyQualifiedClassName is the name of the class that needs to be instantiated using its companion object. It can be TestClass or any class implementing TestTrait
// properties is the map that needs to be pass to the apply method of the companion object.


}

which will when pass class name , will generate an object of the same class by first getting a companion object and then call apply on the companion object passing the map to generate the class instance.

I know we have reflections in scala and I tried few things but to no avail. Here are few things I tried.

  import scala.reflect.runtime.universe

def getInstance(fullyQualifiedClassName: String, properties: Map[String, String]): TestTrait = {
val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
    val module        = runtimeMirror.staticModule(fullyQualifiedClassName)
    val obj           = runtimeMirror.reflectModule(module)

      obj.instance
        .asInstanceOf[TestTrait[String, String]]
        .apply(properties)
        .asInstanceOf[TestTrait[String, String]]

}

Can someone help me to complete def getInstance method. ?





Get a private field via reflection, in Java

I have a Java class named "MyClass" with a private attribute, of type "AnotherClass". MyClass has a private constructor, and "AnotherClass" has public constructor. "AnotherClass" has also a private String field, "value", which is initialized in constructor. I want to access in "Main" class this String.

The first class:

public class MyClass {
    private AnotherClass obj;

    private MyClass() {
        obj = new AnotherClass();
    }
}

The second class:

public class AnotherClass {
    private String value;

    public AnotherClass() {
        value = "You got the private value!";
    }
}

The main class:

public class Main {

    static String name;
    static AnotherClass obj;

    public static void main(String[] args) throws Exception {
        Class myClass;
        myClass = Class.forName("main.MyClass");
        Constructor<MyClass>[] constructors = myClass
            .getDeclaredConstructors();
        for (Constructor c : constructors) {
            if (c.getParameters().length == 0) {
                c.setAccessible(true);
                MyClass myCls= (MyClass) c.newInstance();
                Field myObjField = myClass
                    .getDeclaredField("obj");
                myObjField.setAccessible(true);
                obj = (AnotherClass) myObjField.get(myCls);

                // If "value" is public, the program prints "You got the private value!"
                // So "obj" is returned correctly, via reflection
                // name = obj.value; 
                // System.out.println(name); 

                // Now I want to get the field "value" of "obj"
                Field myStringField = obj.getClass().getDeclaredField("value");
                myStringField.setAccessible(true);

                // This line throws an exception
                name = (String) myStringField.get(obj.getClass());

                System.out.println(name); 
            }
        }
    }
}

I expect to see in the console "You got the private value!", but the program throws an exception:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field main.AnotherClass.value to java.lang.Class

So, I want to retrieve the private field, "value", without modifying "MyClass" and "AnotherClass", and without calling the public constructor from AnotherClass directly in main() . I want to get the value from "obj".





C# compre two classes structure

How to compare and get differences between two classes.

public class Class1{

public string S1{get;set;}
public string S2{get;set;}
public Class2 C3{get;set;}
}

public class Class2{

public string S1{get;set;}
public string S2{get;set;} 
}

public class Class3{

public string S1{get;set;}
public string S2{get;set;}
public string S12{get;set;}
public Class4 C3{get;set;}
}

public class Class4{

public string S1{get;set;}
public string S2{get;set;}
public string S112{get;set;} 
}

At the end I want to know that there is missing member witout creating instances of classes

public string S112{get;set;}   

and

public string S12{get;set;}




lundi 20 avril 2020

Use reflection to iterate over default methods on an interface and call them

public interface IMyInterface {
    default String get() {
        return "help";
    }
}
 Class settings = IMyInterface.class;
IMyInterface target = (IMyInterface) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IMyInterface.class}, (o, method, objects) -> method.invoke(o,objects));
Method[] methods =  settings.getMethods()

for(Method method : methods){
  Object value = method.invoke(target);
}

Doesn't work object is not an instance of declaring class ?





How to dump or write modified java.lang.Class using reflection to file?

I'm trying to update the method annotation value in a java file at runtime. I'm able to update the value and finally, I got the changes. But don't know how to write the updated source code to file. I'm assuming all changes are present in forName. So please let me know any solution to write the modified java source code to file.

try {
     Class<?> forName = Class.forName("test.SortJsonContent");
     Method[] methods = forName.getDeclaredMethods();
     for (Method method : methods) {                
          method.setAccessible(true);
          if (method.isAnnotationPresent(AnnoTest.class)) {
                AnnoTest anno = method.getAnnotation(AnnoTest.class);
                changeAnnotationValue(anno, "test", "new val");                    
           }
      }

    } catch (Exception e) {
            System.err.println("error"+ e);
    }




Create instance of Generic Type from an assembly of other context in C# using refection

I have a Type from some AssemblyContext (plugin code). I know the same assembly is also loaded in default context. I want to have a method that returns the object of the Type from the corresponding assembly in Default Context.

Here is my code

            public object GetService(Type serviceType, IServiceProvider provider)
            {
                try
                {
                    // If same context
                    var defaultService = provider.GetService(serviceType);
                    if (defaultService != null)
                    {
                        return defaultService;
                    }

                }
                catch (InvalidOperationException ex)
                {

                }

                /// The <see cref="serviceType"/> might come from an external assembly.
                /// Try to find a matching type within the assemblies loaded with the <see cref="Provider"/>'s <see cref="AssemblyLoadContext"/>.

                var providerContext = AssemblyLoadContext.GetLoadContext(provider.GetType().Assembly);
                var resolvedAssembly = FindBestMatch(providerContext.Assemblies.ToList(), serviceType.Assembly.GetName());
                Type resolvedType = null;

                if (serviceType.IsGenericType)
                {
                    resolvedType = resolvedAssembly
                                    .GetType(serviceType.GetGenericTypeDefinition().FullName, throwOnError: true)
                                    .MakeGenericType(serviceType.GetGenericArguments());
                }
                else
                {
                    resolvedType = resolvedAssembly.GetType(serviceType.FullName, throwOnError: true);
                }
                var resolvedService = provider.GetService(resolvedType);
                return ImpromptuInterface.Impromptu.DynamicActLike(resolvedService, serviceType);
            }

The FindBestMatch just looks for the assembly though the list-

        Assembly FindBestMatch(IReadOnlyCollection<Assembly> choices, AssemblyName hint)
        {
            if (choices == null) throw new ArgumentNullException(nameof(choices));
            if (hint == null) throw new ArgumentNullException(nameof(hint));

            return choices.FirstOrDefault(choice => choice.GetName() == hint)
                ?? choices.FirstOrDefault(choice => choice.GetName().FullName == hint.FullName)
                ?? choices.FirstOrDefault(choice => choice.GetName().Name == hint.Name);
        }

Now it works fine for non-generics. For generics like ILogger it does create object of type Logger but it throws RunTimeBinderException while trying to invoke methods on those objects. For example, for logger the exception message reads- "'Logger' does not contain a definition for 'LogDebug'".

So, 1. what's going on here?, 2. is there a better way to achieve this?





How to assign attribute to classes methods by convention?

I wanted to make my Controller methods register as [HttpGet] if they have "get" in the method name, the same goes for [HttpPost] if they have "create" etc.

How can I create an "attributeAssigner", that would go over the assembly and do the job?





TypeScript Creating all subclasses of abstract class

I have an abstract class and several classes that extends this class. I want to dynamically get all of the subclasses of that class, so I could create them all.

I tried the following: Typescript - Get all implementations of interface, which works fine, if all of the subclasses are at the same file as the abstract class.

Else, the file of the subclasses is never imported and thus it is never being registered.

Is there any other way to achieve this? Something like Reflection in C#?





dimanche 19 avril 2020

convert java object to json using gson

I am using Java Reflection API to get the objects since I don't know the type of the Object explicitly and I don't have the access to the Classes as well.

if (object != null) {
    HashMap<String, Object> requestDetails = new HashMap<>();
    for (Field field : object.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object value = null;
        try {
            value = field.get(object);
        } catch (IllegalAccessException e) {
            log.error("Could not found the class", e);
        }
        if (value != null) {
            requestDetails.put(field.getName(), value);
        }
    }
    return requestDetails;
}
return object;

Then I wanted to convert it to the JSON Object using Gson.

for (Map.Entry<String, Object> authzRequestDetail : authzRequestDetails.entrySet()) {
    final Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(getStaticTypeAdapterFactory())
            .create();
    JsonElement element = gson.toJsonTree(authzRequestDetail.getValue());
    valueObject.add(authzRequestDetail.getKey(), element);
}
return valueObject;

Since I don't know the type of the class I am getting the error,

Attempted to serialize java.lang.Class: org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint. Forgot to register a type adapter?

Is it possible to convert it to JSON object without knowing the Class of it, Because I don't have the access to the Classes to Downcast and pass it like,(say the Class is accessible ClassA)

JsonElement element = gson.toJsonTree((ClassA)authzRequestDetail.getValue(),ClassA.class);

please note that this objects contain multiple types.





call ef core method with generic type from type name

I have an application logging a list of query to be executed at a later time. So I have a list containing something like this:

class QueryToBeExecutedLater
{
  string sql { get; set; }
  object[] parameters { get; set; }
  string entityTypeFullName { get; set; }
}

And I need to execute them like:

List<QueryToBeExecutedLater> allQueries = ...
foreach(var q in allQueries )
{
    Type elementType = Type.GetType(q.entityTypeFullName);
    var result = await db.Set<elementType>.FromSqlRaw(q.sql,q.parameters).ToListAsync();
}

But of course it doesn't work. I am not all that familiar with reflection. So far I have been able to get the dbSet with this:

List<QueryToBeExecutedLater> allQueries = ...
foreach(var q in allQueries )
{
    Type elementType = Type.GetType(q.entityTypeFullName);
    MethodInfo method = typeof(myDbContext).GetMethod("Set",
                                  BindingFlags.Public | BindingFlags.Static);
    method = method.MakeGenericMethod(elementType);
    var _dbSet = method.Invoke(db,null);

    var result = _dbSet.FromSqlRaw(q.sql,q.parameters);
}

Which of course doesn't work, because: enter image description here

I probably should be doing something like this:

List<QueryToBeExecutedLater> allQueries = ...
foreach(var q in allQueries )
{
    Type elementType = Type.GetType(q.entityTypeFullName);
    MethodInfo method = typeof(myDbContext).GetMethod("Set",
                                  BindingFlags.Public | BindingFlags.Static);
    method = method.MakeGenericMethod(elementType);
    var _dbSet = method.Invoke(db,null);

    var typeReturnedByInvoke_type_of_dbset = **...How Do I Get this type?...**
    MethodInfo _method = typeReturnedByInvoke_type_of_dbset.GetMethod("FromSqlRaw",
                                  BindingFlags.Public | BindingFlags.Static);

    object[] frontParameter = { sql };
    var allParameters = frontParameter.Concat(parameters).ToArray();

    // The "null" is because it's a static method
    var result = _method.Invoke(_dbSet, allParameters);
}

But how do I get the type of the result of method.Invoke? Or is there a way to avoid all these invokes and just cast the result of the first invoke to the right DbSet<elementType> and continue from there without reflection?

Thank you in advance for any help!





How to add a Method and Field in a Lombok Like fashion to a Java Class?

I have the following case:

I have class with a field and a Annotation:


public class TestClass{

   @Property
   private Object testValue;
}

My goal is to create a Method for each annotated field that would create a "boilerplate code in a lombok like fashion" for the Property for each Value that is annotated that should look like this


  public Object getTestValueProperty{
   return testValue;  
  }

I can access the fields over reflection and anotations, And read the Type etc. But there is no Way to "Create" a Method Structure and adding it to the class on runtime.

I looked into the following: http://notatube.blogspot.com/2010/12/project-lombok-creating-custom.html

But I failed to get access the JavacAnnotationHandler to create the new Method. Since this article is 10 Years Old, I would assume this is not up to date anymore and that there are other ways to "inject" a method into a class.

If you could give me any resources or Ideas how to research this topic I would appriciate it.