samedi 29 février 2020

JavaAssist CtClass works, but throws NoClassDefError when invoke constructor

I used this code :

  ClassPool pool = ClassPool.getDefault();

        pool.insertClassPath(new ClassClassPath(ReflectedNBTCompound.class));
        CtClass cl = pool.getCtClass(ReflectedNBTWrapper.class.getCanonicalName());
        CtClass ct = pool.makeClass("NBTCompatibleTileEntity", ctClass);
        ct.addField(new CtField(cl, "nbtField", ct));
        ct.addConstructor(CtNewConstructor.make(
                "public NBTCompatibleTileEntity(){" +
                        " this.nbtField = new skywolf46.NBTUtil.v1_3.NBTData.ReflectedNBTCompound();" +
                        "System.out.println(\"Object created!\");" +
                        "}"

                , ct
        ));
        ct.addMethod(CtMethod.make(
                "public skywolf46.NBTUtil.v1_3.NBTData.ReflectedNBTCompound getNBT(){" +
                        "  return nbtField;" +
                        "}"
                , ct));

        ct.addMethod(CtMethod.make(
                "public void load(" + BukkitVersionUtil.getNMSClass("NBTTagCompound").getName() + " comp){" +
                        "  if(comp.hasKey(\"ReflectedNBT\"))" +
                        "    nbtField = new skywolf46.NBTUtil.v1_3.NBTData.ReflectedNBTCompound(comp.getCompound(\"ReflectedNBT\"));" +
                        "}"
                , ct));
        Class c = ct.toClass();
        c.getConstructor().newInstance();
        Bukkit.getConsoleSender().sendMessage("§5ReflectedNBTWrapper §7| §aInitialized! ");

Error:

java.lang.NoClassDefFoundError: skywolf46/NBTUtil/v1_3/NBTData/ReflectedNBTCompound
        at java.lang.Class.getDeclaredConstructors0(Native Method) ~[?:1.8.0_202]
        at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671) ~[?:1.8.0_202]
        at java.lang.Class.getConstructor0(Class.java:3075) ~[?:1.8.0_202]
        at java.lang.Class.getConstructor(Class.java:1825) ~[?:1.8.0_202]
        at skywolf46.NBTUtil.v1_3.ReflectedNBTWrapper.initBukkit(ReflectedNBTWrapper.java:88) ~[?:?]
        at skywolf46.NBTUtil.v1_3.ReflectedNBTWrapper.onEnable(ReflectedNBTWrapper.java:27) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264) ~[spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:403) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugin(CraftServer.java:381) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugins(CraftServer.java:330) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at net.minecraft.server.v1_12_R1.MinecraftServer.t(MinecraftServer.java:422) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at net.minecraft.server.v1_12_R1.MinecraftServer.l(MinecraftServer.java:383) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at net.minecraft.server.v1_12_R1.MinecraftServer.a(MinecraftServer.java:338) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:272) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:545) [spigot-ram-patched.jar:git-Spigot-79a30d7-acbc348]
        at java.lang.Thread.run(Thread.java:748) [?:1.8.0_202]
Caused by: java.lang.ClassNotFoundException: skywolf46.NBTUtil.v1_3.NBTData.ReflectedNBTCompound
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[?:1.8.0_202]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_202]
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[?:1.8.0_202]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_202]

When I invoke no parameter constructor with reflection, it throws NoClassDefError. I'm sure bukkit loaded all of my project's class, cause It not throws exception when class called with Class.forName(String).

How can I can resolve ClassNotFound with this code?





Reflection on Nested Types adds methods. Is this a bug?

I'm using reflection to obtain methods on a nested type/s and they always have extra methods that don't exist.

The extra methods returned are:

Equals, GetHashCode, GetType, ToString

Is this a bug in .Net or am I missing something? It seems to happen with other nested types also, so I'm trying to understand why?

Public Class TestHasNested

    Public Property bla As String

    Public Class NestedItem

        Public Property MyProperty As Integer

    End Class
End Class




How to get the package (path) of a value?

I would like to get the path of package which defined a value. Given:

package main

import (
    "fmt"
    "reflect"

    "github.com/clipperhouse/jargon/stemmer"
)

func main() {
    valOf := reflect.ValueOf(stemmer.English)
    fmt.Println(valOf)
}

... my desired result is the string github.com/clipperhouse/jargon/stemmer. Here is a playground.

I have tried variations of Type().PkgPath, but I am not interested in the type (which may be defined in yet another package), but rather the package that defined this particular instance value (stemmer.English).





Compiler-like Java Reflection method resolution

I'm programming a method that uses Reflection to find methods the "same way" (not exactly, as you will see) the compiler does. I left Generics out of the scope in this case, as the type parameter does not affect signature of methods (as far as I know).

Basically I want to ask if there's a baked library that already does this and how far are my methods from accomplishing the task in a relatively acceptable way (I don't expect perfect and full resolution, I don't even need static methods).

I could not find the exact spects about how does the compiler actually perform the task, so I made a guess that suits the needs of my environment, however, if possible and not too complex, I'd like to have it done in the proper way for possible complex future uses.

Right now, my assumption is IGNORING overloaded methods with different return types, as it is not a problem with my current problem, but that may be in the future, so I may be interested in taking it into consideration if you have ideas.

So, as I don't have to care about return types, I start by calling a simple

clazz.getMethods();

and then I perform a filter by name. I'm aware I'm totally missing the overrides mentioned abvove here. This is a first approach.

This is how I calculate the distance between a method and the desired arguments: If parent and children are the same instance, then the distance is 0. If not, this methods calls classDistance recursively on children superclass and all directly implemented interfaces. The distance will be the smalles positive distance plus one. (ignoring incompatible ancestors). This solution works for me because right now all the functions I need to call have just one parameter, and the few that have a second one, allways do a perfect match on first parameter on the desired method, so there's only one positive distance to narrow down.

Actual code:

private static Method getBestMatch(List<Method> validMethods, List<Class<?>> classes) {
    if(validMethods.size() == 1) return validMethods.get(0);
    int distance = Integer.MAX_VALUE;
    Method currMethod = null;
    outer_loop:
    for(Method method : validMethods) {
        Class<?>[] methodTypes = method.getParameterTypes();
        int methodDistance = 0;
        for(int i=0; i < methodTypes.length; i++) {
            if(!methodTypes[i].isAssignableFrom(classes.get(i))) continue outer_loop; // Incompatible. Should not happen, but just in case
            methodDistance += classDistance(methodTypes[i], classes.get(i));

        }
        if(currMethod == null || methodDistance < distance) {
            currMethod = method;
            distance = methodDistance;
        }
    }
    return currMethod;
}

Distance calculator:

private static int classDistance(Class<?> parent, Class<?> children) throws IllegalArgumentException{
    if(parent.equals(children)) return 0;
    if(!parent.isAssignableFrom(children)) throw new IllegalArgumentException("children is not assignable to father"); // Should do b4 equals?
    Integer minDistance = null;

    Class<?> superClass = children.getSuperclass();
    if(superClass != null && parent.isAssignableFrom(superClass)) {
        minDistance = classDistance(parent, superClass);
    }
    for(Class<?> directInterface : children.getInterfaces()) {
        if(!parent.isAssignableFrom(directInterface)) continue;
        int interfaceDistance = classDistance(parent, directInterface);
        if(minDistance == null || interfaceDistance < minDistance)  minDistance = interfaceDistance;
    }

    if(minDistance == null) throw new IllegalArgumentException("we found no distance. this is an odd behaviour and definetly a bug, or means this method is not well-thought at all");
    return minDistance + 1;
}

Things I should take into consideration:

  • Should I complain about ambigous methods? As you can see I just pick up the first
  • That overloaded with different type issue... How can I know precedence? If I'm not wrong, compiler allways picks the method of the closest class.
  • That distance calculation looks too simple to be true




Equivalent of VarHandle in Java 8

Is there in Java 8 the equivalent of VarHandle of Java 9 to allow faster access to the properties of an object?





Getting all methods with custom attribute in c# never finds a method

So I created this function to get all methods with the custom attribute ExecuteFromConsole

    [ExecuteFromConsole("test", "help")]
    static void Test(string[] args)
    {
        Debug.Log("Test Ran");
    }

    public void AddAttributeCommands()
    {
        //get all methods with the execute attribute
        var methods = AppDomain.CurrentDomain.GetAssemblies()
                               .SelectMany(x => x.GetTypes())
                               .Where(x => x.IsClass)
                               .SelectMany(x => x.GetMethods())
                               .Where(x => x.GetCustomAttributes(typeof(ExecuteFromConsoleAttribute), false).FirstOrDefault() != null);

        //adds them to commands
        foreach (var method in methods) 
        {
            Debug.Log("Found attribute");
            ExecuteFromConsoleAttribute attribute = (ExecuteFromConsoleAttribute)method.GetCustomAttributes(typeof(ExecuteFromConsoleAttribute), false).First();
            if(!method.IsStatic)
            {
                Debug.LogError("ExecuteFromConsoleAttribute must be used on static functions only");
                continue;
            }
            CommandFunc func = (CommandFunc)Delegate.CreateDelegate(typeof(CommandFunc), method);
            AddCommand(attribute.command, func, attribute.help);
        }
    }

Which worked just fine when I initially tested it but now it will never enter the foreach loop and Debug.log("found attribute") meaning its not finding the method that is clearly right above it with the attribute. AFAIK I didn't modify anything that should have affected this.

Does anybody have an insight on why its not working or if I'm going about it all wrong and there is a better way that I should have been doing instead?

The project is in unity if that affects anything





vendredi 28 février 2020

Accessing function arguments (and their names) during an invocation?

I've got about 50 functions taking anywhere from 2 to 20 positional arguments (required interface for an Excel com add-in).

The all look something like this:

public static string ACustomFunction(string FirstArg, object Arg2, int ThirdArg, ...)
{
    try {
        if(IsErrorValue(FirstArg, out string errorDescription))
            return $"Error: {nameof(FirstArg)} was {errorDescription}";
        if(IsErrorValue(Arg2, out rrorDescription))
            return $"Error: {nameof(Arg2)} was {errorDescription}";
        if(IsErrorValue(ThirdArg, out errorDescription))
            return $"Error: {nameof(ThirdArg)} was {errorDescription}";
        // ... Do some real work
    }
    catch(Exception ex){
        return $"Good Excel formulas don't throw exceptions: {ex.Message}";
    }
}

It ends up generating a ton of error checking code for something fairly repetetive and formulaic.


I would much rather if I could start each function with something like:

if(AnyErrors(Reflection.CurrentMethodInvocation.Args, out errorMessage))
   return errorMessage;

And have some helper method (AnyErrors) loop over the arguments, and if any has an error, return the appropriate error message, including the name of the argument that had the error.


So far the best I can do is to exhaustively list out all arguments and their names for each function - but this feels fragile (prone to omissions when adding new arguments):

string anyErrors = AnyErrors(FirstArg, nameof(FirstArg), Arg2, nameof(Arg2), ThirdArg, nameof(ThirdArg), ...));
if(anyErrors != null)
   return anyErrors;

public static string AnyErrors(params object[] args)
{
   for (int i = 0; i < args.Length; i++)
      if(IsErrorValue(args[0], out string errorDescription))
         return $"Error: {nameof(args[1])} was {errorDescription}";
   return null;
}

Is this something I can do more elegantly, perhaps with some clever reflection? (Preferably something that doesn't carry a large performance penalty - Excel formulas are expected to be snappy).

Thanks





Inject value in parameter of method when executing it

How can a value be dynamically injected for a method parameter? Example:

class A {

  method(@timeStamp() when: string): void {
    console.log(when); // Should output when was the method executed
  }

}




Is it possible to change a method's return type for the method chain?

I am implementing a method, myAssert(String s), it needs to behave like this,

condition1: it can work with isEqualTo(o) in a way of myAssert("test").isEqualTo(someObj) to check if they are 2 equal objects

condition2: it can work with startsWith(String s2) in a way of myAssert("this is a string").startsWith("this is")

Apparently myAssert needs to change its return type to be a string or an object. I know in https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html or https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html there are APIs to get information in a class.

But is there any API I can use to retrieve the information about the method channing?

Any comments are appreciated.





How to read the IISExpressSSLPort dynamically in Visual Studio

Quick question, hopefully a simply answer. When working with a Web Project in Visual Studios, if I enable SSL, it generates an SSL URL.

The problem I'm having is that when I run the application (debugging), it wants to start using http on whatever port that is. So my fix is to basically ..

if (HttpContext.Request.IsLocal == true)
{
   myUriBuilder.Scheme = Uri.UriSchemeHttps;
   myUriBuilder.Port = 44331;
}

I would very much like to be able to dynamically determine what that SSL port is for this project without having to hard code it (code re-usability)

I know that port is located in the .csproj file under the node IISExpressSSLPort, but short of trying to parse up the file, I thought I'd reach out and see if someone knows a way to grab that value in code at runtime.





Make delegate for method at runtime

I found this interesting article Reflection Performance - Create Delegate (Properties C#)

the described approach works great for properties. So I tried to to make it work for Methods, too, but without success.

Methods looks like:

public class Person
{ public string Name { get; set; } }
public class Process
{
    public Person GetPersonByName(string PersonName)
    {
         // lookup person
         return person;
    }
}

my current Approach looks like:

public static Func<object, string, object> BuildMethodAccessor(MethodInfo method)
    {
        var obj = Expression.Parameter(typeof(object), "o");
        var strParam = Expression.Parameter(typeof(string), "strParam");
        //var param = method.GetParameters().Select(p => Expression.Parameter(p.ParameterType, p.Name)).FirstOrDefault();
        var param = Expression.Convert(strParam, method.GetParameters().First().ParameterType);

        Expression<Func<object, string, object>> expr =
            Expression.Lambda<Func<object, string, object>>(
                Expression.Convert(Expression.Call(Expression.Convert(obj, method.DeclaringType), method, param),
                    typeof(object)),
                obj);

        return expr.Compile();

    }

this code generates messages, that for the lambda-declaration a wrong number of Parameters was used. thx a lot for your help!





Converting a string into an attribute in Python [duplicate]

Is it possible to do something like this in Python?

class MyClass():
    def __init__(self):
        someValue = 42

        str = 'a'
        # self.a = someValue
        str = 'xyz'
        # self.xyz = someValue       

Essentially what I want to achieve is by reading the value of str (say the value of str resolves to 'myValue'), the code adds an additional attribute (self.myValue) into the class.





jeudi 27 février 2020

Using concepts for checking if a type T has a field F

The following concept checks if a type T has a public field foo:

template<typename T>               
concept has_field_foo = requires { 
    T::foo;                       
}

Is there a way to implement a generic concept that would check if a type T has a public field F, something like (pseudo code... the field F cannot be passed like this):

template<typename T, typename F>               
concept has_field = requires { 
    T::F;
}




Set or change frequency band channels

actually i m about to programm an app, which should save a given wifi enterprise network to the phone. So it is important to set the frequency band and the channel.

From another thread, i found out, that there is a hidden method called "setfrequencyband". With the reflection (explained here: Cannot resolve public method setFrequencyBand in WifiManager class) it is possible to use it, but i cant find any method, with that i can set the channels. I have searched a lot but couldnt find anything that could solve my problem.

Somebody can help me please? Thanks so far.

Greetz





Instantiating an object of a type parameter using reflections

I know that when working with Generics we can't instantiate an object of unknown type i.e the statment : T var = new T() will give compile time error , I tried it using Reflections after some search , but its not compiling and gives me the error I will mention at the end

Code :

public class HelloWorld{
     public static void main(String []args){
        Pair<Integer> obj = new Pair<Integer>(Integer.class);
                            obj.<Integer>func();             
    }
}
class Pair<T>
{
    T  var;
   <T> Pair(){}
   <T> Pair(Class<T> reflection){
             var = reflection.newInstance() ;  
             }

   <T> void func(){
   System.out.println(var);
   }
}

Error :

HelloWorld.java:12: error: incompatible types: T#1 cannot be converted to T#2
             var = reflection.newInstance() ;  
                                         ^
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in constructor <T#1>Pair(Class<T#1>)
    T#2 extends Object declared in class Pair

I am trying to find the cause of the error but can't reach it





mercredi 26 février 2020

Mysterious EXC_BAD_ACCESS error on a strongly referenced variable

TL;DR

I have a class with no public initializers or instances that passes an instance of itself to a closure in another class. It does this through a mirror of the other class. When I go to access that instance from within the closure, I'm getting a EXC_BAD_ACCESS error, but other things passed to the function are clearly accessible and do not result in a bad access error. I have no idea why.

Detailed Explanation

I've been trying to figure out a way to implement class-specific access control, where multiple specific classes have sole access to another class containing variables and functions to be shared between them. All other classes would not have such access. Kind of like a static class, or a Singleton pattern, but with specific, class-named access control.

I thought I had something that would actually work in pure swift, (which is nice for me since I don't know Objective-C, and only started on swift about 16 months ago.) It's done in an almost anti-swift manner, so just bear with me - my goal is to start with something functional and move it towards elegance and beauty from there.

Even though I'm reasonably confident it should all work, I'm encountering a EXC_BAD_ACCESS error in a very unexpected place.

The "class-specific private" class that you are not allowed to access an instance of unless you are on its "okay" list, we can call the Restricted class.

The class(es) that is(are) allowed access to the Restricted class we can call the Accessor class(es).

The programmer must tell the Restricted class to call a function from the Accessor, and "drop in" an instance of the Restricted class by passing it as a parameter to that function. You do this by passing in the name of the function to be called, an instance of the Accessor class on which to call said function, and any parameters that the function would need in addition to the Restricted class instance.

I could make an enormous switch in the Restricted class, each case of which properly calls each function indicated on each of the Accessor classes...but to get around that excessive overhead/setup, I have the name of the function to be called on the Accessor classes passed in as a string, and accessed through a mirror. Since mirrors only reflect properties and not functions, the function must be a property with an assigned closure, instead of a traditional function.

We can call these closures DropClosures, since their purpose is to have the shared, Restricted class dropped into them. In fact we could call this whole pattern the "DropClosure Pattern". (Or maybe anti-pattern, I know it's kind of gruesome as-is.)

The properties of the "shared" instance of the Restricted class are stored internally as a private static dict (as json, basically). To generate an actual instance of itself, the Restricted class uses a private initializer that accepts that dict as a parameter. After a DropClosure runs with said initialized instance, the Restricted class uses a Mirror of that instance to store any changes back in the "shared" dict, and the instance will go out of scope unless a reference is made to it. So after each DropClosure completes its run, the instance passed to it is more or less useless as a representation of the "shared" aspect of the class, intentionally so.

I only do this because there is no way to require that all references to a certain weak reference also be weak. I don't want a class with access to the weak reference to assign a strong reference to the same instance and keep it in memory, that would defeat the access control goal by allowing the instance to be shared outside of its access scope. Since I can't force the instance to expire once the closure has completed, the next best thing is to remove the motivation for doing so by making the object no longer connected to the shared source after the closure completes.

This all theoretically works, and will compile, and will not throw any swift exceptions when run.

The Accessor (or any class that has an instance of an Accessor) calls RestrictedClass.run(), the run code validates the Accessor instance, finds the DropClosure in that instance, and passes in an instance of the Restricted class to that closure.

However, whenever I try to access that instance from within the DropClosure, it gives me the aforementioned bad access error, seemingly on a C or Objective-C level.

As far as I can tell, the instance should be accessible at this point, and none of the variables being used should be dropping out of scope yet.

At this point I'm totally spitballing - is it possible that there is something in the background that prevents a class with no public initializers from being passed through a mirror? Does it have to do with passing it into a closure called from that mirror? Is there some kind of hidden weak reference that's making the instance get ARC'd?

Code:

import Foundation

typealias DropClosureVoid<T: AnyObject & AccessRestricted> = (_ weaklyConnectedInterface: WeaklyConnectedInterface<T>, _ usingParameters: Any?)->Void
typealias DropClosureAny<T: AnyObject & AccessRestricted> = (_ weaklyConnectedInterface: WeaklyConnectedInterface<T>, _ usingParameters: Any?)->Any?

enum AccessError : Error {
    case InvalidFunction
    case InvalidAccessClass
}
protocol AccessRestricted {
    static func run<T:AnyObject>(_ closureName:String, in classObject: T, with parameters:Any?) throws
    static func runAndReturn<T:AnyObject>(_ closureName:String, in classObject: T, with parameters:Any?) throws -> Any?
}
///This class contains an instance that should be expected to only temporarily represent the original, even if a strong reference is made that keeps the value in scope.
class WeaklyConnectedInterface<T:AnyObject> {
    weak var value:T?
    init(_ value: T) {
        self.value = value
    }
}
class Accessor {

    let restrictedClassPassable:DropClosureVoid<RestrictedAccessClass> = { weaklyConnectedInterface, parameters in
        print(weaklyConnectedInterface) // **EXC_BAD_ACCESS error here**
        //note that the error above happens even if I pass in the instance directly, without the WeaklyConnectedInterface wrapper. 
        //It's clearly an issue that occurs when trying to access the instance, whether the instance is wrapped in a the class that makes a weak reference to it or not, which means that it is inaccessible even when strongly referenced.
        if let parameterDict = parameters as? [String:String] {
            print(parameterDict["paramkey"] ?? "nil")
            print(weaklyConnectedInterface)
            weaklyConnectedInterface.value?.restrictedVariable = "I've changed the restricted variable"
        }
    }

    let anotherRestrictedClassPassable:DropClosureAny<RestrictedAccessClass> = { weaklyConnectedInterface, parameters in
        if let parameterDict = parameters as? [String:String] {
            print(parameterDict["paramkey"] ?? "nil")
            print(weaklyConnectedInterface.value?.restrictedVariable as Any)
            return weaklyConnectedInterface.value?.restrictedVariable
        }
        return nil
    }

    func runRestrictedClassPassable() throws {
        let functionName = "restrictedClassPassable"
        print("trying validateClosureName(functionName)")
        try validateClosureName(functionName)//this is in case you refactor/change the function name and the "constant" above is no longer valid
        print("trying RestrictedAccessClass.run")
        try RestrictedAccessClass.run(functionName, in: self, with: ["paramkey":"paramvalue"])
        let returningFunctionName = "anotherRestrictedClassPassable"
        print("trying validateClosureName(returningFunctionName)")
        try validateClosureName(returningFunctionName)
        print("trying RestrictedAccessClass.runAndReturn")
        let result = (try RestrictedAccessClass.runAndReturn(returningFunctionName, in: self, with: ["paramkey":"ParamValueChanged"]) as! String?) ?? "NIL, something went wrong"
        print("result is \(result)")
    }

    func validateClosureName(_ name:String) throws {
        let mirror = Mirror(reflecting: self)
        var functionNameIsPresent = false
        for child in mirror.children {
            if child.label != nil && child.label! == name {
                functionNameIsPresent = true
                break
            }
        }
        guard functionNameIsPresent else {
            print("invalid function")
            throw AccessError.InvalidFunction
        }
    }
}
extension Mirror {
    func getChildrenDict() -> [String:Any]
    {
        var dict = [String:Any]()
        for child in children
        {
            if let name = child.label
            {
                dict[name] = child.value
            }
        }
        return dict
    }
}


class RestrictedAccessClass:AccessRestricted {

    private static var shared:[String:Any] = [
        "restrictedVariable" : "You can't access me!"
    ]
    private static func validateType<T>(of classObject:T) throws {
        switch classObject {
        case is Accessor:
            return
        default:
            print("Invalid access class")
            throw AccessError.InvalidAccessClass
        }
    }
    var restrictedVariable:String
    private init() {
        restrictedVariable = "You can't access me!"
    }
    private init(from json:[String:Any]) {
        restrictedVariable = json["restrictedVariable"] as! String
    }
    static func run<T:AnyObject>(_ closureName:String, in classObject: T, with parameters:Any?) throws {
        print("trying validateType(of: classObject) in run")
        try validateType(of: classObject)
        for child in Mirror(reflecting: classObject).children {
            if let childName = child.label {
                if childName == closureName {
                    let dropClosure = child.value as! DropClosureVoid<RestrictedAccessClass>
                    let selfInstance = RestrictedAccessClass(from:shared)
                    let interface = WeaklyConnectedInterface(selfInstance)
                    dropClosure(interface, parameters)
                    runCleanup(on: selfInstance)//parses any data changed by the end of the drop closure back into the dict for use in future instances. This means you mustn't try using the instance in an async closure. The correct way to do this would be to call run inside of an async closure, rather than putting an anync closure inside of the drop closure.
                    _ = interface.value
                    return
                }
            }
        }
    }
    static func runAndReturn<T:AnyObject>(_ closureName:String, in classObject: T, with parameters:Any?) throws -> Any? {
        print("trying validateType(of: classObject) in runAndReturn")
        try validateType(of: classObject)
        for child in Mirror(reflecting: classObject).children {
            if let childName = child.label {
                if childName == closureName {
                    let dropClosure = child.value as! DropClosureAny<RestrictedAccessClass>
                    let selfInstance = RestrictedAccessClass(from:shared)
                    let interface = WeaklyConnectedInterface(selfInstance)
                    let result = dropClosure(interface, parameters)
                    runCleanup(on: selfInstance)//parses any data changed by the end of the drop closure back into the dict for use in future instances. This means you mustn't try using the instance in an async closure. The correct way to do this would be to call run inside of an async closure, rather than putting an anync closure inside of the drop closure.
                    _ = interface.value
                    return result
                }
            }
        }
        return nil
    }
    private static func runCleanup(on instance:RestrictedAccessClass) {
        shared = Mirror(reflecting:instance).getChildrenDict()
        //once this function goes out of scope(or shortly thereafter), the instance passed will become useless as a shared resource
    }


}

Code to encounter error:

I just put this in a new project's AppDelegate.application(didFinishLaunching). You can put all of the code above and below, in order, in a playground and it will break in the same spot, but not as clearly.

let accessor = Accessor()
do {
    try accessor.runRestrictedClassPassable()
}
catch {
    print(error.localizedDescription)
}




Getting Constructor from Java Class that would be called for argument types, not requiring exact argument & parameter type match

Is there any way in Java (or in a Java library) to get the Constructor from a Class that would be called for the given arguments / argument types (not requiring exact argument & parameter type matches, instead including supertypes)?

i.e. I know about Class#getConstructor(Class<?>), but that only returns exact matches.

e.g., the following code throws a NoSuchMethodException, whereas I want to get the Constructor for A(CharSequence), as that's what would be called if I ran, e.g., A(""):

public class A {

    public A(Object o) {}
    public A(CharSequence cs) {}

    public static void main(String[] args) throws Exception {
        Constructor c = A.class.getConstructor(String.class);
        c.newInstance("");
    }
}

I imagine that such a method would also potentially throw an exception indicating that multiple constructors match, so it can't choose without the argument types being made more specific (like through explicit casts).

I'd also want to find this functionality for Methods.

Thanks.





mardi 25 février 2020

Does the use of `is` in a when expression over a sealed class result in reflection at runtime?

In Java, if I have a class hierarchy like so:

private interface Foo { }

private class FooBar implements Foo { }

private class FooZoo implements Foo { }

And then I have a function like so:

public int Return0IfFooBarElseIfFooZooReturn1ElseReturn2(Foo foo) {
    if (foo instanceof FooBar) {
        return 0;
    } else if (foo instanceof FooZoo) {
        return 1;
    } else {
        return 2;
    }
}

At run time, reflection will be used to determine the type of foo. In an ideal world, we would like to avoid having our code use reflection. In addition, as far as I know, there is no way to create a sealed type hierarchy in Java, meaning you will always need to provide an else branch to have the code compile.

However in Kotlin you can create a sealed type hierarchy, like so:

sealed class Foo {
  object FooBar : Foo()
  object FooZoo : Foo()
}

And you can then write a when expression to switch on the type and return a value like so:

fun return0IfFooBarElseReturn1(foo: Foo) = when (foo) {
  is Foo.FooBar -> 0
  is Foo.FooZoo -> 1 
}

There is an interesting property about this; namely, there is no need for an else, because the when expression is exhaustively checking the sealed type hierarchy. So, from this property, can the compiler derive enough information in order to compile bytecode which somehow is not going to use reflection at runtime to determine if the passed instance is of a given type?

Or in other words, is there any difference (with regards to reflection) at run time between the Kotlin code above, and the Kotlin code below:

interface Foo

class FooBar : Foo { }

class FooZoo : Foo { } 

fun return0IfFooBarElseReturn1(foo: Foo) = when (foo) {
    is FooBar -> 0
    else -> 1
}

I am asking this, because generally as programmers, we would like to avoid reflection (where possible), but the official Kotlin docs for sealed classes show an example of switching on an instance using is (https://kotlinlang.org/docs/reference/sealed-classes.html). I also do this a fair bit in the code I do at work, and whilst I don't really see any issue with doing it, some co-workers have voiced concerns as it looks like a code smell.





Custom Attribute Named Arguments Not Populated

I have made an custom attribute, but I want to be able to pass a named arguments with it.

Here is the attribute below. enter image description here enter image description here

Everything looks alright to me, but every time I run it, the Roles property is equal to null. Any normal parameters I user with the attribute look fine.

I am using this in asp.net core 2.2

What am I missing?





Get Values from inherited when base type is given back

Situation: IdentityUser is inherited by AppUser.

AppUser has a few properties more.((int)ExClientNr and (string)Category)

On top

UserManager <IdentityUser> userManager

request

var user = await userManager.FindByEmailAsync(Input.Email);

When I hover over user (of type IdentityUser) in runtime, I see all AppUser properties with values in the list.

But when I type

var exClientNr = User.ExClientNr; 

the field ExClientNr or Category is not recognized in the intellisense.All fields of IdentityUser are of cause.

User.Getype() gives me {Name="AppUser" FullName="namespace.Models.AppUser"} so it is even aware of his type.

Question: Can someone tell me how to get the value from those extra properties from this object.





C# Object Property to Load Values from List

I have a class with a property: public object something { get; set; }

I obtain a list of values from a method, say List<string> myList and I would like to load each value into property something without using expando etc.

Basically, I am trying to to:

SomePrototypeClass myClass = new SomePrototypeClass();

foreach (string item in myList)
{
myClass.something.Add (item)
}

Is this possible? (Reflection or somehow?) Could anyone advise please?





How can i pass a lambda expression to the method which is called using reflection

I'm working on just another version of Onion Architecture using EF in core environment. I have some mapping that i want it to be applied on almost every table i have, and since the mapping is somehow logical in my scenario, i want to close the gap in my and my co-workers mind, reducing further data corruption.

So i wen't through Reflection step by step, trying to achieve the following scenario:

for (all registered model in context) {
  if(model has IXyz interface) {
    * builder apply mapping on entity
  }
}

The star sign ():* The mapping i want to configure at * point is as following:

builder.Entity<Sample>().HasQueryFilter(m => EF.Property<bool>(m, nameof(IDeletableEntity.IsDeleted)) == false);

I tried many things, but none worked; I jumped from error to error, at both run time & compile time:

1.

System.ArgumentException: 'Static method requires null instance, non-static method requires non-null instance.'

2.

System.ArgumentException: 'Method 'Boolean b__6_0(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder1[Template.Domain.Models.Sample])' declared on type 'Template.Data.Configurations.ApplicationDbContext+<>c__61[Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1[Template.Domain.Models.Sample]]' cannot be called with instance of type 'Template.Data.Configurations.ApplicationDbContext''

3.

Error CS1660 Cannot convert lambda expression to type 'Expression' because it is not a delegate

The latest state of my code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Template.Domain.Interfaces;
using Template.Domain.Models;

namespace Template.Data.Configurations
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Sample> Samples { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            Debugger.Launch();

            var modelBuilderMethods = builder.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
            MethodInfo desiredModelBuilderMethod = modelBuilderMethods.FirstOrDefault(modelBuilderMethod => modelBuilderMethod.Name == nameof(builder.Entity) && modelBuilderMethod.IsGenericMethod && modelBuilderMethod.IsGenericMethodDefinition && modelBuilderMethod.GetParameters().Length == 0); //Entity<T>() Method

            //builder.Entity<Sample>().HasQueryFilter(m => EF.Property<bool>(m, nameof(IDeletableEntity.IsDeleted)) == false);
            foreach (var entityType in builder.Model.GetEntityTypes())
            {
                if (entityType.ClrType.GetInterfaces().Any(w => w == typeof(IDeletableEntity)))
                {
                    var entityGenericMethod = desiredModelBuilderMethod.MakeGenericMethod(entityType.ClrType);
                    var entity = entityGenericMethod.Invoke(builder, new object[0]);
                    var entityTypeBuilder = entity.GetType();
                    var entityTypeBuilderMethods = entityTypeBuilder.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                    MethodInfo desiredEntityTypeBuilder = entityTypeBuilderMethods.FirstOrDefault(entityTypeBuilderMethod => entityTypeBuilderMethod.Name == nameof(EntityTypeBuilder.HasQueryFilter) && !entityTypeBuilderMethod.IsGenericMethod && !entityTypeBuilderMethod.IsGenericMethodDefinition); //HasQueryFilter(Expression<Func<T, bool>> filter) Method


                    var queryFilterMethod = this.GetType()
                        .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
                        .FirstOrDefault(w => w.Name == nameof(SetQueryFilters)
                                             && w.IsGenericMethod
                                             && w.IsGenericMethodDefinition
                                             && w.GetParameters().Length == 0)
                        ?.MakeGenericMethod(entity.GetType());

                    var lambdaExpression = queryFilterMethod.Invoke(this, new object[0]);
                    desiredEntityTypeBuilder.Invoke(entity, new object[]
                    {
                        lambdaExpression
                    });

                }
            }
        }

        private Expression<Func<T, bool>> SetQueryFilters<T>()
        {
            var func = new Func<T, bool>(m=> EF.Property<bool>(m, nameof(IDeletableEntity.IsDeleted)) == false);
            var exp = Expression.Default(typeof(ApplicationDbContext)); //Expression.Constant(this);
            var methodCallExpression = Expression.Call(exp, func.Method);

            var expression = Expression.Lambda<Func<T, bool>>(methodCallExpression);
            return expression;
        }

    }
}

namespace Template.Domain.Interfaces
{
    public interface IDeletableEntity
    {
        bool IsDeleted { get; set; }
    }
}


using System.ComponentModel.DataAnnotations.Schema;
using Template.Domain.Interfaces;

namespace Template.Domain.Models
{
    public class Sample : IDeletableEntity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public bool IsDeleted { get; set; }
    }
}

Note to Debug this code you need to call "Update-Database" in "Package Manager Console".

Thank you, Hassan.





How can I use "R.id object = new R.id();" with Build-Tools 3.6.0?

I have to use different layouts for different build flavors where in one flavor there are ui elements that don't exist in the other flavor.

Earlier I just set elements invisible/gone but now I have a NestedScrollView with a child fragment that contains a RecyclerView. The child needs a button in one flavor that the other flavor must not have. If I just set it invisible or gone the layout doesn't work properly (doesn't scroll and height is much too low).

I copied the layout xml to the path of the flavor and removed the button and used reflection in fragment code to know if the button exists and implement it's code.

    Class<R.id> c = R.id.class;
    R.id object = new R.id();
    Field[] fields = c.getDeclaredFields();

    for (Field field : fields)
    {
        field.setAccessible(true);
        try
        {
            if (field.getName().equals("TheButton"))
            {
                Button tBtn = tView.findViewById((Integer) field.get(object));
                if (tBtn != null)
                    tBtn.setOnClickListener(...);
            }
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
    }

After updating to Gradle build tools from 3.5.3 to 3.6.0 I get

error: id() has private access in id R.id object = new R.id();

for the line

R.id object = new R.id();

when trying to build. At the moment I just keep uinge the old build tools but that's no permanent solution, I think.

Can I do something else? I would like to get rid of reflection but if it's really the only way to go it should work with latest build tools...





C# Conversion of recursive iteration of properties' values for List<> property

I have the following method which I use to iterate through all properties (just properties) in my classes and print on screen their names and values they hold, if any.

        public static void PrintProperties(object obj, int indent = 1)
        {
        if ( obj == null )
            return;
        string indentString = new string (' ', indent);

        Type objType = obj.GetType ();
        PropertyInfo[] properties = objType.GetProperties ();

        foreach ( PropertyInfo property in properties )
        {
            object propValue = property.GetValue (obj, null);
            var elems = propValue as IList;
            if ( elems != null )
            {
                foreach ( var item in elems )
                {
                    PrintProperties (item, indent + 3);
                }
            }
            else
            {
                if ( property.PropertyType.Assembly == objType.Assembly )
                {
                    Console.WriteLine("{0}{1}:", indentString, property.Name);

                    PrintProperties (propValue, indent + 2);
                }
                else
                {
                    Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
                }
            }
            }

Unfortunately, I change a property in one of my Classes from string to List<string> to accommodate for multiple values that I had to assign there, and now I get error System.Reflection.TargetParameterCountException: 'Parameter count mismatch.' which I don't know how to fix, and most probably is because I have a property that is List. How can i fix so that when I encounter such a property, to list all its values? Could someone help me please?





lundi 24 février 2020

Diff Two Strings Line-By-Line in Java using Diff-Match-Patch

I was looking for an easy way to do a Myers Diff on two Strings line-by-line in Java.

According to this, the Google diff-match-patch library has this feature. But, in the Java version, those methods referenced are protected and/or package-protected!

I couldn't find another library that (1) does this, and (2) appears to be well-maintained.

So I ended up using reflection to get the Google one to let me do this. I want to avoid anyone having to re-implement it, so I will post what I did as an answer.





How to Instantiate a Class from a Dictionary

Given a class, how can an instance of it be created from a dictionary of fields? Here is an example to illustrate my question:

from typing import Tuple, Mapping, Any


def new_instance(of: type, with_fields: Mapping[str, Any]):
    """How to implement this?"""
    return ...


class A:
    """Example class"""

    def __init__(self, pair: Tuple[int, int]):
        self.first = pair[0]
        self.second = pair[1]

    def sum(self):
        return self.first + self.second


# Example use of new_instance
a_instance = new_instance(
    of=A,
    with_fields={'first': 1, 'second': 2}
)




Find all specific types, with reflection, in assemblies loaded by the application

I have a system where there are commands, for a chat bot, scattered in different part of the code. I find, and register, them all through reflection using this code:

member private this.RegisterCommands() =
    let t = typeof<IBotCommands>
    t.Assembly.GetTypes()
    |> Seq.filter (fun x -> x.GetInterface(t.Name) <> null)
    |> Seq.iter (fun x ->
        (
            let i = (Activator.CreateInstance(x)) :?> IBotCommands
            botCommands.[i.Name()] <- i
            i.Initialize(this)
        )
    )

It's in F#, but I think the method calls give away what it does if you're more familiar with C#.

So, I do Assembly.GetTypes, keep the ones where GetInterface has the interface name I'm looking for and then I instantiate them.

This works well, but only within its own assembly. My question is how can I expand this to all assemblies loaded by the app (but the system ones to not waste time)?





ThreeJS diamond reflection and refraction

Im experimenting with three js and trying to make diamond. I found a couple of examples with shaders and without but what cache my curiosity is this sample from sketchfab. Its seems that its not using shader but there is some trick how diamond look is achieved, like you using backside of diamond texture while moving camera and adding other effects, or maybe im wrong.

https://sketchfab.com/3d-models/gems-92ff52fe0f2e44bc877c133191df7195

I tried to render first backside of diamond with cubemap environment and use rendertarget cubecamera, then i render second scene where im using previous scene as a texture with reflection and refraction but no results so far.

Does someone have any idea how this can be done, i would really like to hear your opinions how you would bulid this? Thanks.





Kotlin reflect/resolve original type of generic template parameter

How can I figure out which type has generic template parameter?

package tutorial.test.reflection

import kotlin.reflect.KClass
import kotlin.reflect.KType

interface ModelElement
interface Parentable<T : ModelElement>

interface Parent : ModelElement

interface Interface1<PARENT_TEMPLATE : ModelElement> : Parentable<PARENT_TEMPLATE>
interface Interface2 : Interface1<Parent>

// Returns just all classifiers in the inheritance hierachy
fun getAllSupertypes(cls: KClass<*>): List<KType> = cls.supertypes.let {
    val types = it.toMutableList()
    cls.supertypes.forEach { types.addAll(getAllSupertypes(it.classifier as KClass<*>)) }
    return types.filter { it.classifier != Any::class }
}

fun main(args: Array<String>) {
    val t = getAllSupertypes(Interface2::class)
    t.forEach {
        println(it)
        if(it.classifier == Parentable::class) {
            it.arguments.forEach {
                println("\t-> ${it.type} ${(it.type?.classifier == Parent::class)}")
                // The template parameter must be "tutorial.test.reflection.Parent" but is PARENT_TEMPLATE
            }

        }
    }
}

Output

tutorial.test.reflection.Interface1

tutorial.test.reflection.Parentable -> PARENT_TEMPLATE false

(it.type?.classifier == Parent::class) should results true. How can I resolve the generic template parameter 'PARENT_TEMPLATE' as the Interface Parent from the inheritance hierarchy?





get members value, name and custom name from enum type with its name

i want to get a string from user and show him a list of enums member and its value. for example i have this enum

public enum exampleEnum
    {
        [MyCustomProperty(customName = "نام1")]
        member1 = 1,

        [MyCustomProperty(customName = "نام2")]
        member2 = 2,

    }

help me for create this function

public List<enumResult> GetEnumDetailWithName(string enumName)
{
 ???

 return result;// {name:'member1',value:1,customName='نام1'},{name:'member2',value:2,customName='نام2'}
} 

i have write this code but not complete in this lines get enum from all assembly and its done then get all members of enum currectly then for any member of enum add a member to result list , filling name is true but i cant fill Value and CustomName Field ...

     public List<enumDetail> GetEnumDetailWithName(string enumName)
    {
        var enumFullName = $"Bamdad.PublicEnum.Enums+{enumName}";
        var assemblyList = AppDomain.CurrentDomain.GetAssemblies();
        Type type = null;
        foreach (var assembly in assemblyList)
        {
            type = assembly.GetType(enumFullName);
            if (type == null)
                continue;
            if (type.IsEnum)
                break;
        }

        if (type == null)
            return null;


        //until this line get enum currectly
        var members = type.GetMembers(BindingFlags.Public | BindingFlags.Static).Where(q=> q?.DeclaringType?.Name == enumName).ToList();
        var properties = type.GetProperties();
        if (!members.Any()) return null;

        var result = new List<enumDetail>();

        //get members currectly
        foreach (var mem in members)
        {

            var resultItem =  new enumDetail()
            {
                Name = mem.Name, // true
                Value = 0,       // i cant get
                CustomName = "???" // i cant get
            };

            result.Add(resultItem);
        }
        return result;
    }

please help me





dimanche 23 février 2020

How to programatically retrieve the arguments for a method

As a homework project I have been asked to create a bunch of classes in a hierarchy, which take different parameters in their constructors, and allow a user to interactively create objects of such classes. For simplicity, let's assume that the classes are Base and Child, with Child extending Base. Any future class in the project would extend Base or one of its subclasses.

Although the focus of the project is not writing elegant or maintainable code, I am trying write such code.

Ideally, after figuring out what object the user wants to instantiate, I would have a way of figuring out which parameters are necessary to create such an object and pass that list to the method in charge of retrieving them from the user. I had thought of a static method, getNecessaryArguments() such as:

public class Base {
    public static List<String> getNecessaryArguments() {
         return Arrays.asList("name", "age");
    }

    public Base(String name, String age) {
        ...
    }
}

public class Child extends Base {
    public static List<String> getNecessaryArguments() {
         final List<String> baseArgs = Base.getNecessaryArguments();
         baseArgs.addAll(Arrays.asList("position"));
    }

    public Child(final String name, final String age, final String position) {
        super(name, age);
        ...
    }

I would then do something like UserInterface.requestParameters(XXX.getNecessaryArguments()).

There are several obvious issues with this code, though:

  1. Two lists of arguments need to be maintained in parallel for each class: the actual arguments to the constructor and arguments returned by getNecessaryArguments().
  2. The class which Child extends has to be explicitly mentioned in its getNecessaryArguments(), since super() cannot be used in static contexts.

This all opens up the possibility of out-of-sync issues if the design changes in the future.

What would be the best way of handling these issues so that the code can adapt to some design changes? I thought of reflection, but I think you cannot retrieve argument names from it, only the method signature.





Can not get Type of LinkedList`T with Type.GetType(string)

I am able to get type information of List<T>, Dictinary<TK, TVal> etc. by:

Type.GetType("System.Collections.Generic.List`1[System.String]")
Type.GetType("System.Collections.Generic.Dictionary`2[System.String,System.String[]]")

But failing to get type information of LinkedList<T>:

Type.GetType("System.Collections.Generic.LinkedList`1[System.String]") // Returns NULL
Type.GetType("System.Collections.Generic.LinkedList`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") // Also returns NULL

Inspecting the assembly of LinkedList<string>

typeof(LinkedList<decimal>).Assembly

Gives:

System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Using .NET Standart 2.0.3.





samedi 22 février 2020

Haxe Reflection Method to Access a Static Field?

I'm looking for a way to use reflection to get and set static fields of a Class. Is that possible, or is that too dynamic for Haxe?





ClassNotFoundException although class exists and is loaded

I am building a modular application which contains template classes in its core module (executed by the user) and loads implementations for these classes from .jar files in a certain directory on every startup.

The loading process of these implementations looks like this:

Collection<Class<?>> output = Lists.newArrayList();
JarFile jarFile = new JarFile(path);
Enumeration<JarEntry> jarEntries = jarFile.entries();

URL[] urls = { new URL("jar:file:" + path + "!/") };
URLClassLoader classLoader = URLClassLoader.newInstance(urls);

while (jarEntries.hasMoreElements()) {
  JarEntry jarEntry = jarEntries.nextElement();
  if(jarEntry == null
          || jarEntry.isDirectory()
          || !jarEntry.getName().endsWith(".class")){
    continue;
  }

  ...

  int ignoreClass = ".class".length();
  String className = jarEntry.getName().substring(0,jarEntry.getName().length()-ignoreClass);
  className = className.replace('/', '.');

  Class implementationClass = classLoader.loadClass(className);
  Class<?> outputClass = this.loadToClassPath(path, implementationClass);
  output.add(outputClass);
  continue;

}


private Class<?> loadToClassPath(String path, Class toLoad) throws NoSuchMethodException,
      MalformedURLException,
      InvocationTargetException,
      IllegalAccessException,
      ClassNotFoundException {
  URLClassLoader loader = (URLClassLoader) KelpApplicationRepository.class.getClassLoader();
  Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
  addURL.setAccessible(true);
  addURL.invoke(loader, new File(path).toURI().toURL());
  return loader.loadClass(toLoad.getName());
}

It compiles, but I get the following runtime error:

[17:51:24 ERROR]: de/pxav/kelp/core/sidebar/version/SidebarVersionTemplate initializing Kelp v0.1-SNAPSHOT (Is it up to date?)
java.lang.NoClassDefFoundError: de/pxav/kelp/core/sidebar/version/SidebarVersionTemplate
    at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.8.0_171]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[?:1.8.0_171]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[?:1.8.0_171]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[?:1.8.0_171]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[?:1.8.0_171]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[?:1.8.0_171]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[?:1.8.0_171]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_171]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[?:1.8.0_171]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_171]
    at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814) ~[?:1.8.0_171]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_171]
    at de.pxav.kelp.core.application.inject.VersionBinderModule.implementationsOf(VersionBinderModule.java:214) ~[?:?]
    at de.pxav.kelp.core.application.inject.VersionBinderModule.lambda$configure$1(VersionBinderModule.java:75) ~[?:?]
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) ~[?:1.8.0_171]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[?:1.8.0_171]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[?:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[?:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[?:1.8.0_171]
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) ~[?:1.8.0_171]
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) ~[?:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:1.8.0_171]
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) ~[?:1.8.0_171]
    at de.pxav.kelp.core.application.inject.VersionBinderModule.configure(VersionBinderModule.java:73) ~[?:?]
    at com.google.inject.AbstractModule.configure(AbstractModule.java:62) ~[?:?]
    at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:340) ~[?:?]
    at com.google.inject.spi.Elements.getElements(Elements.java:110) ~[?:?]
    at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:138) ~[?:?]
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:104) ~[?:?]
    at com.google.inject.Guice.createInjector(Guice.java:96) ~[?:?]
    at com.google.inject.Guice.createInjector(Guice.java:73) ~[?:?]
    at com.google.inject.Guice.createInjector(Guice.java:62) ~[?:?]
    at de.pxav.kelp.core.KelpPlugin.onLoad(KelpPlugin.java:41) ~[?:?]
    at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugins(CraftServer.java:297) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.craftbukkit.v1_8_R3.CraftServer.reload(CraftServer.java:739) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.Bukkit.reload(Bukkit.java:535) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:25) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:641) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchServerCommand(CraftServer.java:627) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at net.minecraft.server.v1_8_R3.DedicatedServer.aO(DedicatedServer.java:412) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:375) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [spigot.jar:git-Spigot-db6de12-18fbb24]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_171]
Caused by: java.lang.ClassNotFoundException: de.pxav.kelp.core.sidebar.version.SidebarVersionTemplate
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_171]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_171]
    at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814) ~[?:1.8.0_171]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_171]
    ... 45 more

I am wondering why, because the .class file of SidebarVersionTemplate exists in the core module. Maybe it has to do with the extends keyword in the implementation class? Does this keyword load classes by default in Java?

implementation class:

public class SidebarVersion extends SidebarVersionTemplate {

template class:

public abstract class SidebarVersionTemplate {

Any ideas? Thanks in advance





How to get the source code of a file where an object is created in Python?

In my main.py I have the following Python code:

from tasks import SimpleTask
from reflectors import Reflector

task = SimpleTask()

source_code = Reflector().get_source_code(task)

I want to get the source code of main.py from inside the Reflector.get_source_code() using only the parameter task passed.

If I do the following in Reflector.get_source_code() using Python's inspect module:

def get_source_code(self, task):
  return str(inspect.getsource(inspect.getmodule(task)))

I get the source code of tasks module where SimpleTask class is defined.

However, I want to get source code of main.py (the file where task object is created).

I have managed to do the following:

source_code = Reflector().get_source_code(lambda: task)

def run(self, task_callback):
  source_code = str(inspect.getsource(inspect.getmodule(task_callback)))

However, I don't like the lambda: task syntax.

Is there any way to achieve this without the lambda hack?

I would be grateful.





vendredi 21 février 2020

How would I convert a int to enum value at runtime when I have a string and an integer?

What I have is a string variable that is the name of a enum. I have the integer of the enum. How would I convert that into instance of the enum itself?

Enum TestEnum
    {
        One = 1,
        Two = 2,
        Three = 3
    }

string str = "TestEnum";
int intValue = 2;

I see many posts that require you to have an instance of the enum to get it's like this highly upvoted answer.

I need to do this at runtime.





How can plugins be loaded dynamically and on-demand in MEF?

When our application is running, we want it to occasionally poll for new plugins and load them if it finds any. We don't just want plugins loaded at startup. Is this possible with MEF? We've done it already with reflection, but MEF gives a nice plugin framework and we would like to use it if possible.





Go: How to avoid dynamic assertion in wrapper functions?

In the simplified code example below, we perform tens of different API calls using the Go library from our vendor.

Vendor library provides us with a definition of API call bodies:

// body of api call A
type requestBodyA struct {
    aa string
    bb int32
}

// body of api call B
type requestBodyB struct {
    id string
}

And with functions which performs the calls for us:

// fn performs api call A
func callCreateA(body requestBodyA) {
    fmt.Println("Value of body is: ", body)
    // makes api call using body requestBodyA
}

// fn performs api call B
func callCreateB(body requestBodyB) {
    fmt.Println("Value of body is: ", body)
    // makes another api call using body requestBodyB
}

We use those to create our own CRUD functions, where we read config files and perform create/read/update/delete calls:

func createA() {
    bodyA := requestBodyA{
        aa: "asdasfsd",
        bb: 15,
    }

    // api retry loop
    for i := 1; i <= 3; i++ {
        // do some pre-checks (generic)

        callCreateA(bodyA)

        // check for errors (generic)
        // check if error is recoverable (generic)
        // if not return error (generic)
        // if yes use the for loop and try the call again in 1,2,3,5,8,13, .. seconds (generic)
    }
}

func createB() {
    bodyB := requestBodyB{
        id: "someUniqueId",
    }
    for i := 1; i <= 3; i++ {
        // do some pre-checks (generic)

        callCreateB(bodyB)

        // check for errors (generic)
        // check if error is recoverable (generic)
        // if not return error (generic)
        // if yes use the for loop and try the call again in 1,2,3,5,8,13, .. seconds (generic)
    }
}

As you can see in functions createA, createB we repeat a lot of generic code (pre-checks, error handling, retry loop and lot more) in every CRUD fn we create. As we're dealing with 30+ resources and each have their own create, read, update, destroy API call function, we have the same code copied 100+ times.

I'd like to move all the generic stuff to some genericApiCaller() and give it the call body as one param and name or a pointer to the API call function as a second param.

Problem 1: callCreateA and callCreateB needs the "body" of different types. It would be way easier if they consume interface{}, but these functions are coming from vendor SDK and it would not be smart to modify them (update reasons, etc). How to assert "body interface{}" of genericApiCaller() to "body requestBodyA" or "body requestBodyB" dynamically? Runtime assertion is not possible in Go, but I didn't find any nice solution for it.

Problem2: How to pass functions with different kinds of parameters as a parameter to genericApiCaller()?

Any idea of how to approach it will be appreciated :-) Thank you very much.

https://play.golang.org/p/incf-NEaSJ3





JUnit5-Jupiter: Composed (="meta") annotation does not resolve to annotation definition

I defined my own JUnit annotation:

@ParameterizedTest
@MethodSource("myorg.qa.ccrtesting.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})
public @interface CcrStandardTest {
}

Then, I was able to use that annotation in my tests:

@CcrStandardTest
public void E0010_contact_standard (String testData) {
...
  • My run configuration:
    JVM options: -ea
    Class: myorg.qa.ccrtesting.ccrstandardtests.CcrStanConTest - This was suggested by the IDE (and is verified to point to the correct class, which holds my prototype test method)

However, this results in: jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [public void...

  • I tried removing String testData from the test method signature but then JUnit is not executing any tests: No tests found

  • When I add @Test above my prototype test method, it executes but:

    1. It seems like none of the annotations I defined under @CcrStandardTest are applied
    2. IDE suggests suspicious combination @Test and parameterized source
      (I already know @ParameterizedTest implies @Test, just not sure why IDE is able to find the custom annotation but JUnit isn't?)




Java : Is it possible to deserialize objects without reflection

My understanding is that deserializing any object uses reflection underneath, always, no matter what be the case.

Heard somebody advocating the contrary.

Please help out in validating this understands ng. Is there any such technique in Java (or any other language) which does not depends upon reflection.





Load dynamically a file, and run a function inside

I have several launch files in my directory (e.g. "my_script.launch.py") and their content is pretty similar to this file:

import launch
import launch.actions
import launch.substitutions
import launch_ros.actions


def generate_launch_description():
    return launch.LaunchDescription([
        launch.actions.DeclareLaunchArgument(
            'node_prefix',
            default_value=[launch.substitutions.EnvironmentVariable('USER'), '_'],
            description='Prefix for node names'),
        launch_ros.actions.Node(
            package='demo_nodes_py', node_executable='talker', output='screen',
            node_name=[launch.substitutions.LaunchConfiguration('node_prefix'), 'talker']),
    ])

All of them have some imports at the top and a generate_launch_description() function, that returns an object which I want to inspect.

I want to implement this function

def get_generate_launch_description_per_path(path):
   pass

that executes the convenient function of the python file on that path and thus returns the LaunchDescription object so I can manipulate it afterwards. Any idea? Probably will need some kind of reflection or dynamic load.





jeudi 20 février 2020

How to combine JUnit annotations into a custom annotation?

(Using OpenJDK-13 and JUnit5-Jupiter)

The problem is that my unit tests each make use of a not-small JUnit annotation system, something like this:

@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})

This makes test authoring a little tedious, test code a little long and of course, when a change is needed, it's a chore!

Was wondering if I could create my own JUnit annotation: @CcrStandardTest, which would imply all of the annotations above?

I also tried shifting the annotations up in the class definition (hoping they would then apply to all methods of the class), but the compiler says no: "@ParameterizedTest is not applicable to type"





get model using string

I'm trying to access a Model in Laravel app through its Class Name, but I'm getting the following error:

Class 'Asset' not found

Though, I've already imported this Model. Here's my code:

<?php
namespace App\Services;
use App\Models\Asset as Asset;
use App\Models\Benefit\BenefitGroup as BenefitGroup;
use App\Models\Benefit\EmployeeDependent as EmployeeDependent;
use App\Models\Country as Country;
use App\Models\Employee\Education as Education;
use App\Models\Employee\EducationType as EducationType;
use App\Models\Employee\Employee as Employee;
use App\Models\Employee\EmployeeVisa as EmployeeVisa;
use App\Models\Employee\VisaType as VisaType;
use App\Models\Note as Note;
use App\Models\PaidTimeOff\Policy as Policy;
use App\Models\PaidTimeOff\TimeOffType as TimeOffType;
use Illuminate\Database\Eloquent\Model;
class ACLService
{
    public function getDefaultPermissions($roleType)
    {
        //Array to append all default permissions in single array without extra indexing
        $permissions=[];
        $models=['Asset', 'Employee', 'Education', 'EducationType', 'VisaType', 'EmployeeVisa', 'BenefitGroup', 'EmployeeDependent',
            'Policy', 'TimeOffType','Country', 'Note'];
        foreach ($models as $model) {
            $permissions=$this->getModelPermissions($model, $roleType, $permissions);
        }
    }
    public function getModelPermissions($model, $roleType, $currentPermissions)
    {
        $data=$model::getDefaultPermissionsForThisModel($roleType, $currentPermissions);
        return $data;
    }
}

If I pass

App\Models\Asset

instead of

Asset

then the error gets resolved but I don't want to pass data in this format because it'll increase the work amount if we ever get to change (in future) the Model's location in the project.

This is an incomplete project and we'll definitely change the models' location.

I'm looking for a cleaner solution.





How to count function calls for unittesting?

I use my own small unittesting framework to test my code.

Sometimes I need the functionality to count how often a function of a fake object is called. Like this:

IDatabase fakeDb = new FakeDatabase();
IResult result = new Foo().ToTest(fakeDb);

//Some other tests

UTest.Equal(fakeDb.FakeCloseCalled(), 1);

So at the moment my FakeDatabase-class looks like this:

class FakeDatabase : IDatabase
{
    //All the other code

    public int FakeCloseCalled
    {
        get;
        private set;
    }

    public void Close()
    {
        FakeCloseCalled++;
    }
}

So, everytime I want to know how often a function of my fake objects was called I have to create a property for this in my FakeClass.

So I wonder if there is a more "generic" way to do this. e.g. profilers and some unittest-frameworks seem to be able to count the calls to functions.

So is there a more generic way to count the calls to Close without creating a property every time?





How is c# reflection a runtime event?

Every definition says C# reflections is used to determine type of object in runtime. Can the type of an object change in runtime? Can anybody please provide me an example.





mercredi 19 février 2020

Java reflection , throwing NPE for methods of another class

public class SolutionConfigOverrideEnginePropertiesFacadeImpl implements SolutionConfigOverrideEnginePropertiesFacade { private SolutionConfigOverrideEnginePropertiesService solutionConfigOverrideEnginePropertiesService;

@Override
public SSCEnginePropertiesModel getEngineSettingAttributes()
{
    return getSolutionConfigOverrideEnginePropertiesService().getEngineSettingAttributes();
}

@Override
public void overrideEngineSettingProperties()
{

I am using reflection to call this class and invoke the overrideEngineSettingProperties method, but the getEngineSettingAttributes method is throwing null pointer exception. How do we load this method or invoke this method along with the above overrideEngineSettingProperties .





Using reflection instead of a long switch statement

Hey so I have a pretty long switch statement that calls a method based on a string like so

private void callMethod(String name) {
    switch(name) {
        case "blah":
            blah();
            break;
        case "method":
            method()
            break;
    }
}

etc.

So I used reflection to shorten the code

try {
    Method method = ClassName.class.getDeclaredMethod(name, args);
    method.invoke(args);
} catch (NoSuchMethodException e) {
    // switch default
}

Just wondering if using reflection like this is bad on memory/performance. I only call this function every so often.





Get description attribute of an enum *subset*

I know how to get the description of every enum. I am trying to figure out how to get it of a subset.

Here's what I have, which I trust shows the intent of what I'm aiming for:

public enum ModelType : int
{
    /// <summary>
    /// No model type. For internal use only.
    /// </summary>
    [Description("NA")]
    _NA = 0,  

    [Description("Literal Model")]
    Literal = 1,

    [Description("Linear Model")]
    Linear = 2,

    [Description("Curve Model")]
    Curve = 3
}


var values = Enum.GetValues(typeof(ModelType))
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .ToArray();

var attributes = values.GetMembers() // this is wrong
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);




Get all property names and values from a generic object C#

We have way too many tables on Index pages throughout our MVC app and we keep making more. I would like to come up with a way to handle any object that needs to be shown in a tabular form. My idea was to make the a partial view that takes in a collection of generic objects and then builds the table. I have figured out how I wan't to handle most of the front end, but striping the values off of this generic object has become a nightmare.

I simply want to access this object kinda like a list or array. I want to put the first prop value here .... and then the second here......I won't know what their names are and I really don't care to. Whatever the value, I just want to display it.

I am close. I know I am somewhat in the right place, but I have never used reflection besides with a container like autofac and I am out of my element.

@foreach (var item in Model.Collection)
{
    //TODO - figure out how to access values in generic object via reflection

    Type t = item.GetType();
    PropertyInfo prop = t.GetProperty("Id");
    var properties = t.GetProperties();
    var value = properties.First().ToString();

    Type[] typeParameters = t.GetGenericArguments();
    var r = t;

    List<string> values = new List<string>();

    Type myType = item.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

    foreach (PropertyInfo ish in props)
    {
        object propValue = prop.GetValue(item, null);

        values.Add(propValue.ToString());
    }
}

![ ]1





Enforce method signature using annotations

I have written a custom annotation that I use to find methods that can be invoked via a IoT platform. It's a method level annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirectMethod {

    String value();

}

I look this annotation up in runtime, and to have the call succeed, the expected signature must be:

@DeviceMethod("metod")
public ReturnType methodName(final String data) {...}

i.e, the return type and the input parameters are crucial.

Is there any way to have an annotation be "smart" when its target type is METHOD? Like integrated IDE warnings and such. Or do I simply have to process each annotation manually at startup and have the startup procedure fail if any method breaks my intended method contract?





Scala dynamic import

How can I dynamically import packages/classes in scala?

Example: can I have a code like this or similar?

object Test {
   def main(args: Array[String]) {
    val pack = "java.util.List"
    import pack
   }
}




mardi 18 février 2020

Haskell: Get caller function name

In Haskell, is there a way to get the caller function name? Of course I could hard-code it, but that turns into a maintenance burden: If someone were to rename the function, nothing is forcing them to rename the hard-coded name (especially with mass find/replace).

A contrived example:

f1 :: String
f1 = "f1" -- can this be automated?




Exception on opening DataSet Visualizer for .Net Core 3.1 in Visual Studio 2019

When trying to use the magnifing glass on one of my DataSet or DataTable in my .Net Core 3.1 WPF Project I get a System.IO.FileLoadException with following text:

Could not load file or assembly 'DataSetVisualizer.DebuggeeSide, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. General Exception (0x80131500)

Stack trace:

at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext) at System.Reflection.Assembly.Load(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext) at System.Reflection.Assembly.Load(AssemblyName assemblyRef) at Microsoft.VisualStudio.DebuggerVisualizers.DebuggeeSide.Impl.ClrCustomVisualizerDebuggeeHost..ctor(String debuggeeSideVisualizerTypeName, String debuggeeSideVisualizerAssemblyName, String[] probePaths) at Microsoft.VisualStudio.DebuggerVisualizers.DebuggeeSide.Impl.ClrCustomVisualizerDebuggeeHost.Create(String debuggeeSideVisualizerTypeName, String debuggeeSideVisualizerAssemblyName, String[] probePaths)

I narrowed the cause for this problem down to my recently implemented method to load assemblies from subfolders at runtime, which I wrote based on Reza Aghaei's answer on my last question.

In narrowed it down to the subscription on the AppDomain.CurrentDomain.AssemblyResolve event, but couldn't find a way to solve it yet.

AppDomain.CurrentDomain.AssemblyResolve += (obj, arg) =>
{
    var name = $"{new AssemblyName(arg.Name).Name}.dll";
    var assemblyFile = referenceFiles.Where(x => x.EndsWith(name))
        .FirstOrDefault();
    if (assemblyFile != null)
        return Assembly.LoadFrom(assemblyFile);
    throw new Exception($"'{name}' Not found");
};

It doesn't matter if I am trying to view the DataSet in one of the loaded assemblies or the startup application.

I would like to keep working with this method to load assemblies at runtime, but since I am working with a lot of DataSets being able to use the DataSet Visualizer is crucial for me.

Any suggestions?





How do I get at the contents of a private reflect.Value in go?

I'm trying to make a general purpose debug printer for complex data types because %v has a tendency to just print pointer values rather than what they point at. I've got it working with everything up until I have to deal with structs containing reflect.Value fields.

The following demo code runs without error: (https://play.golang.org/p/qvdRKc40R8k)

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    i int
    R reflect.Value
}

func printContents(value interface{}) {
    // Omitted: check if value is actually a struct
    rv := reflect.ValueOf(value)
    for i := 0; i < rv.NumField(); i++ {
        fmt.Printf("%v: ", rv.Type().Field(i).Name)
        field := rv.Field(i)
        switch field.Kind() {
        case reflect.Int:
            fmt.Printf("%v", field.Int())
        case reflect.Struct:
            // Omitted: check if field is actually a reflect.Value to an int
            fmt.Printf("reflect.Value(%v)", field.Interface().(reflect.Value).Int())
        }
        fmt.Printf("\n")
    }
}

func main() {
    printContents(MyStruct{123, reflect.ValueOf(456)})
}

This prints:

i: 123
R: reflect.Value(456)

However, if I change MyStruct's R field name to r, it fails:

panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

Of course, it's rightly failing because this would otherwise be a way to get an unexported field into proper goland, which is a no-no.

But this leaves me in a quandry: How can I gain access to whatever the unexported reflect.Value refers to without using Interface() so that I can walk its contents and print? I've looked through the reflect documentation and haven't found anything that looks helpful...





How to add environment variable to evulator mono sharp

I wrote a program that runs dynamic runtime codes. I am using Evulator class to do this. This is setup lines for executer.

 this._reportWriter = new StringWriter();
        this._settings = new CompilerSettings();
        this._settings.ReferencesLookupPaths.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "xxx.dll"));
        this._settings.ReferencesLookupPaths.Add(AppDomain.CurrentDomain.BaseDirectory);
        this._settings.LoadDefaultReferences = true;
        this._settings.AssemblyReferences.Add("xxx.dll");
        this._evaluator = new Evaluator(new CompilerContext(this._settings, new StreamReportPrinter(_reportWriter)));

I am running this program concurrently. In our program, the xxx.dll uses environment_variable to start server. So that, I have to set environment_variable for each processes in itself with different values. Can i set environment variable in evaluator settings just for that process ?

Thanks





How to verify that a Type can be passed to a generic method in C# also restore generic parameter types based on passed arguments

Let me try to explain what I mean. For example I have the following code:

public static class MyClass
{
   public static void DoSmthWithCollection<T>(IEnumerable<T> collection)
   {
       ...
   }
}

Of course, compiler would allow to pass to it an object of List<int> type. Moreover, the compiler will figure out that the type T for the method is resolved to int type based on the argument type.

I need to do the same only dynamically, either by using System.Reflection or Roslyn. Say I get the MethodInfo for the method, I get the generic ParameterInfo. Is there any easy way to figure out that an object of type typeof(List<int>) actually fits to be an argument to the method and that when you pass it, the method resolves T to int type? And I am talking about some relatively easy solution without examining types and subtypes and the generic type constraints. I think at least Roslyn should have one, since this is what the C# compiler is doing.

Thanks for your help.





How to restart the spring boot application in the middle of endpoint and then start executing from there?

I want to restart the spring boot application while I am in middle of an endpoint method

Lets consider this example:

    @RequestMapping(value = "/CreateView")
    public ResponseView createView()
    {
//      Here I write something to one of my files at runtime

//          //some more code
//      -------> SOMEWHERE I WANT THE SPRING BOOT APPLICATION TO RESTART<---------
//      And here I want to access those new writing (via reflection) that I have done at the runtime

    }

Is there any way to do the above?





Java reflection error Java.lang.NoSuchMethodException, but method exists

I can't get to work java reflection in Spring boot with Controller and JdbcTemplate.

Default controller looks like:

public class DefaultController {

private static final Logger logger = LoggerFactory.getLogger(DefaultController.class);

public JsonResponseDataModel selectOneAuto(Long id, Class<?> repository, HttpServletResponse response){

    final JsonResponseDataModel result = new JsonResponseDataModel();
    System.out.println("The name of class is " + repository.getName());

    Method[] methods = repository.getMethods();
    for (Method method : methods) {
        System.out.println("Method: " + method.getName());
    }

    try {
        //Method method = repository.getClass().getMethod("selectOne", Long.class);
        Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);
        method.invoke(repository, id);

        logger.info("selectOneAuto : id={} ", id);
    } catch (EmptyResultDataAccessException e) {
        result.setEmptyResultDataAccessException("id", id.toString());
    } catch (DataAccessException e) {            
        e.printStackTrace();            
    } catch (NoSuchMethodException e) {            
        e.printStackTrace();            
    } catch (IllegalAccessException e) {            
        e.printStackTrace();            
    } catch (InvocationTargetException e) {            
        e.printStackTrace();            
    }
    return result;
}

}

Inside CompanyRepository class is defined selectOne method with Long input:

@Transactional(readOnly=true)
     public CompanyModel selectOne(Long id) {
     CompanyModel result = null;
     final String sql = "SELECT * FROM company WHERE id=?";
     return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CompanyRowMapper());
}

When I create a new class "CompanyController extends DefaultController" and call method selectOneAuto:

selectOneAuto(id, new CompanyRepository().getClass(), response);

Then it ends with error on line "Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);"

"Java.lang.NoSuchMethodException: java.lang.Class.selectOne(java.lang.Long)"

But the for loop inside "selectOneAuto" method outputs method named "selectOne". What is wrong here?





Create instance using Activator

I got some troubles with Activator.CreateInstance. It throws "Constructor on type not found" exception.

Here is the method where error occurs:

private static void InitializeInternalProperty(Calculation calculation, Type type, IDataProvider dataProvider, params string[] precedants)
{
    PropertiesCollection precedantsCollection = new PropertiesCollection(); //Properties collection implements IKeyedCollection
    foreach (string precedant in precedants)
    {
        precedantsCollection.Add(calculation.properties[precedant]);
    }
    calculation.properties.Add((Property)Activator.CreateInstance(type, dataProvider, precedantsCollection));
}

Here is the constructor, i am trying to use:

internal CountryRiskPremium(IDataProvider dataProvider, PropertiesCollection precedants)
{
    Name = Names.CountryRiskPremium;
    InitLinks(precedants);
    _dataProvider = dataProvider;
}

I also tried:

object[] arguments = new object[2];
arguments[0] = dataProvider;
arguments[1] = precedantsCollection;
calculation.properties.Add((Property)Activator.CreateInstance(type, arguments));




avoid magic strings in c# [duplicate]

I have this extension method in order to retrieve the validation error message of a property:

public static string GetValiAttriError(this object instance, string propertyName)
{
    var attrType = typeof(ValidationAttribute);
    var property = instance.GetType().GetProperty(propertyName);
    var r = (ValidationAttribute)property.GetCustomAttributes(attrType, false).First();
    return r.ErrorMessage;
}

and this is how I call it:

UserForReg userForRegi = new UserForReg();
var errorMessage = userForReg.GetValiAttriError("PropertyName");

Instead of having to use a magic string like in this case "PropertyName" for the name of the property I could love to have a typed solution to avoid error during execution when the name of a property changes.

Something linke this would be wonderful (without even the need of an instance of UserForReg):

var errorMessage = GetValiAttriError(UserForReg.PropertyName);

Is it possible?





lundi 17 février 2020

Unable to retrieve enum type if the definition is located inside a class via reflection

How to retrieve the enum type if the enum is defined within a class?

Adapted from the code here:

namespace GetEnumReflectionTesting
{
    enum Foo { Bar = 5 }
    public class MyClass
    {
        enum Foo { Bar =6}
    }


    class Program
    {
        static void Main()
        {
            // Get the assembly containing the enum - Here it's the one executing
            var assembly = Assembly.GetExecutingAssembly();


            var enumType = assembly.GetType("GetEnumReflectionTesting.Foo"); //this obtains the GetEnumReflectionTesting.Foo
            var enumBarValue = enumType.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue, (int)enumBarValue);

            var enumType2 = assembly.GetType("GetEnumReflectionTesting.MyClass.Foo"); //but instead of GetEnumReflectionTesting.MyClass.Foo, this returns a null!
            var enumBarValue2 = enumType2.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue2, (int)enumBarValue2);
        }
    }
}

Here's something interesting, enumType retrieves the GetEnumReflectionTesting.Foo as expected, but enumType2 instead of retrieve GetEnumReflectionTesting.MyClass.Foo, it returns a null!

So what is the robust way to retrieve the enum type regardless of whether it is defined within a class, or not?

Note that in my scenario, the Foo enum is defined within a class, and I get it from third party vendor which I can't change. So don't suggest me moving the Foo enum outside of the class.





How can I use reflection to instance a class which takes ReadOnlySpan as a constructor argument?

I have code like this:

    // lookup the object type, instance passing the data as constructor
    //all registered types must implement ctor passed ReadOnlySpan<byte>
    public static object InterpretPayload(ReadOnlySpan<byte> bytes)
    {
        var key = bytes[0];
        if (!TypeLookup.ContainsKey(key))
            return null;
        Type type = TypeLookup[key];
        var created = Activator.CreateInstance(type, bytes);
        return created;
    }

TypeLookup maps numeric values to class types, in a weird sort of factory method pattern. However when changing my codebase to use ReadOnlySpan over byte[] I now get a compiler error that bytes isn't an object, which it isn't.

Is there another way to do this? I believe Activator tries to find the best ctor based on what I pass in, seems I need to do this more explicitly. Can I use reflection another way or have I found a case reflection can't emulate calling the ctor directly?





How to get the class type of the contents of an Iterable in scala?

Say I have a method like this:

def getClassFromIterable(iterable: Iterable[Any]): Class[_] = {
  iterable.head.getClass
}

This will get the class of the top of the list, but will fail if the list is empty.
How can I get the class of a passed list that has zero or more elements?