mercredi 31 juillet 2019

Some package classes of classpath can not be found when I want to trace a Package symbol and inspect a class or object

There is such a premise.

organization: "com.xxx"

project A
  com.xxx.a.aa
  com.xxx.a.mm
project B dependsOn A
  com.xxx.b.bb
  com.xxx.b.nn
  com.xxx.b.runtime
    Extractor.scala
project C dependsOn B
  com.xxx.c.cc
  com.xxx.c.oo
  com.xxx.c
    Main.scala

Extractor.scala loads the classpath under the package _root_ and tries type checking.

def run(): Vector[universe.Symbol] = {
    recursivePackageExplore(
      Vector(rootPackage)
    )
  }

  private final def rootPackage: universe.Symbol = universe.runtimeMirror(getClass.getClassLoader).RootPackage.info.typeSymbol

  @tailrec
  private final def recursivePackageExplore(selfPackages: Vector[universe.Symbol],
                                            result: Vector[universe.Symbol] = Vector.empty): Vector[universe.Symbol] = {
    selfPackages match {
      case x if x.isEmpty => result
      case _              =>
        val (packages, modules) = selfPackages.flatMap(_.typeSignature.members).distinct.collect {
          case x if selfPackages.contains(x) =>
            None -> None
          case x if x.isPackage                                                         =>
            Some(x) -> None
          case x if x.isModule && !x.toString.startsWith("package object") && !x.isAbstract                                         =>
            None -> Some(x)
        } match {
          case x => x.flatMap(_._1) -> x.flatMap(_._2)
        }

        recursivePackageExplore(
          packages,
          result ++ recursiveModuleExplore(modules)
        )
    }
  }

  @tailrec
  private final def recursiveModuleExplore(n: Vector[universe.Symbol],
                                           result: Vector[universe.Symbol] = Vector.empty): Vector[universe.Symbol] = {
    n match {
      case accessibleSymbol if accessibleSymbol.isEmpty => result
      case accessibleSymbol                             =>
        recursiveModuleExplore(
          accessibleSymbol.withFilter(_.isModule).flatMap(_.typeSignature.members).collect {
            case x if x.isModule => x
          },
          result ++ accessibleSymbol.filter(_.accepted))
    }
  }

When I ran the Extractor from Main, I expected that most classes under project A, B and C would be returned in result. However, it seems that only classes of some packages under project B could actually be detected.

This works as expected if you set the run function to macro. In the case of runtime reflection, Symbol(package).typeSignature.members was considered to load the classpath. Did I make a mistake?





How can I use reflection to give a string to a class

Instructions

Create an implementation of the Robot class with the following traits:

  • Name the derived class Sonny
  • Sonny's version should be 2.0.0.0
  • Sonny's greeting should be "Hello, my name is Sonny" (bonus points for using reflection)
  • Add a fourth law: "A robot may not harm humanity, or, by inaction, allow humanity to come to harm"

    [assembly: AssemblyVersionAttribute("2.0.0.0")] public class Program { public void Main() { Assembly thisAssem = typeof(Program).Assembly; AssemblyName thisAssemName = thisAssem.GetName(); Version ver = thisAssemName.Version;

    Sony sony = new Sony(ver);
    
    Console.WriteLine("Greeting: {0}", sony.Greeting());
    Console.WriteLine("Robot Version: {0}", sony.Version);
    
    List<string> laws = sony.GetLaws();
    foreach (string law in laws)
    {
        Console.WriteLine("Law #{0}: {1}", laws.IndexOf(law) + 1, law);
    }    
    } 
    }
    public class Sony : Robot
    {
    private readonly List<string> _laws = new List<string>
    {
    "A robot may not injure a human being or, through inaction, allow a human being to come to harm.",
    "A robot must obey the orders given it by human beings, except where such orders would conflict with the First Law.",
    "A robot must protect its own existence as long as such protection does not conflict with the First or Second Law.",
    "A robot may not harm humanity, or, by inaction, allow humanity to come to harm"
    };
    
    public Sony(Version version) : base(version)
    {
    Version = Version;
    }
    
    public override string Greeting()
    {
    return "Hello, my name is Sonny";
    }
    
    public override List<string> GetLaws()
    {
    return _laws;
    }
    }
    
    public abstract class Robot
    {
    private readonly List<string> _laws = new List<string>
    {
    "A robot may not injure a human being or, through inaction, allow a human being to come to harm.",
    "A robot must obey the orders given it by human beings, except where such orders would conflict with the First Law.",
    "A robot must protect its own existence as long as such protection does not conflict with the First or Second Law."
    };
    
    protected Robot(Version version)
    {
    Version = version;
    }
    
    public abstract string Greeting();
    
    public Version Version { get; set; }
    
    public virtual List<string> GetLaws()
    {
    return _laws;
    }
    
    

    }

I have completed all the tasks but I would like to get the bonus points for reflection on the greeting. How can I achieve this?





Launch JavaFX project using reflection

I have a program, that downloads a Git repository, builds it and launches defined Main class. It works properly with ordinary projects, but when I want to launch a JavaFX project, I get strange errors like:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at Main.main(Main.java:31)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: app.UI_Main
    at javafx.application.Application.launch(Application.java:260)
    at app.UI_Main.main(UI_Main.java:31)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: app.UI_Main
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at javafx.application.Application.launch(Application.java:248)
    ... 6 more

My Main class is:

public class Main {
    private static final String GIT_ADDRESS = "https://github.com/lerryv/CheckCheckerDesktop";
    private static final String MAIN_PATH = "app/";
    private static final String MAIN_CLASS = "app.UI_Main";
    public static void main(String[] args) throws GitAPIException, IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Git.cloneRepository().setURI(GIT_ADDRESS).setDirectory(Paths.get("./dir/").toFile()).call();
        Collection<String> result = compile(Paths.get("./dir/src/").toFile());
        String command = System.getProperty("java.home") + "/../bin/javac -d dirOut -cp \".:json-simple-1.1.jar\" " + result.join(" ");
        Runtime.getRuntime().exec(command);
        URLClassLoader urlClassLoader = URLClassLoader.newInstance(
                new URL[]{
                        new File("dirOut/").toURI().toURL()
                }
        );
        Class clazz = urlClassLoader.loadClass(MAIN_CLASS);
        Method main = clazz.getDeclaredMethod("main", String[].class);
        assert Modifier.isStatic(main.getModifiers());
        main.invoke(null, (Object) args);
    }
    private static Collection<String> compile(File directory) {
        assert directory.isDirectory();
        Collection<String> result = new Collection<>();
        boolean hasFiles = false;
        for (File file: directory.listFiles()) {
            if (file.isDirectory()) {
                result.addAll(compile(file));
            } else {
                if (!hasFiles) {
                    String path = file.getAbsolutePath();
                    String extension = path.substring(path.lastIndexOf(".") + 1);
                    if (extension.equals("java")) hasFiles = true;
                }
            }
        }
        if (hasFiles) result.add(directory.getAbsolutePath() + "/*.java");
        return result;
    };
}

At first I thought it cannot find the class, but when I removed the method.invoke statement, errors disappeared. Why does it happen and are there any workarounds?





mardi 30 juillet 2019

how to initialize class and specify generic type of class by reflection

1, The custom class definition:

public class MyClass<T> {

    private T property;

    public MyClass() {
    }

    public MyClass(T property) {
        this.property = property;
    }


}


2, normal initialization as following is worked:

MyClass<String> stringMyClass = new MyClass<>();
stringMyClass.setProperty("hello");
System.out.println("stringMyClass:" + stringMyClass.getProperty());


Requirments:

The requirments is to initialize instance by reflection. The T will be specified dynamically. Such as:

Constructor<MyClass> con = MyClass.class.getDeclaredConstructor(String.class);
con.setAccessible(true);
MyClass hello = con.newInstance("hello");
System.out.println("property:" + hello.getProperty());

but reflection code above is not working, error message as following:

Exception in thread "main" java.lang.NoSuchMethodException: test.mytest.MyClass.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at test.mytest.Main.main(Main.java:8)

How to initialize it by reflection ?





Mapping data classes with non-constructor methods

I have the following model classes set up in my Android project which I'm attempting to convert from one type to the other (API Response models to Room Database Entity models) but am running into an issue which I cannot seem to get past.

data class TeamResponse(
    val id:String,
    val name:String,
    val teamMembers:List<TeamMember>
)

data class TeamMemberResponse(
    val id:String,
    val firstName:String,
    val lastName:String
)

data class TeamEntity(
    val id:String,
    val name:String,
    val lastRefresh:Date
) {
    @Ignore var teamMembers:List<TeamMemberEntity>
}

data class TeamMemberEntity(
    val id:String,
    val firstName:String,
    val lastName:String,
    val lastRefresh:Date
)

To convert these, I set up the kotlin-reflect JAR in the project and was attempting use Extension methods to convert these from one object type to the other:

fun Team.toTeamEntity() = with(::TeamEntity) {
    val propertiesByName = Team::class.memberProperties.associateBy { it.name }
    val teamEntity = this@toTeamEntity
    callBy(parameters.associate { parameter ->
        parameter to when (parameter.name) {
            TeamEntity::lastRefresh.name -> Date()
            TeamEntity::teamMembers.name -> {
                val teamMembers: List<TeamMember> = propertiesByName[paramName]?.get(this@toTeamEntity) as List<TeamMember>
                teamMembers.map { it.toTeamMemberEntity() }
            }
            else -> propertiesByName[parameter.name]?.get(this@toTeamEntity)
        }
    })
}

fun TeamMember.toTeamMemberEntity() = with(::TeamMemberEntity) {
    val propertiesByName = TeamMember::class.memberProperties.associateBy { it.name }
    callBy(parameters.associate { parameter ->
        parameter to when (parameter.name) {
            TeamMemberEntity::lastRefresh.name -> Date()
            TeamMemberEntity::user.name -> (propertiesByName[parameter.name]?.get(this@toTeamMemberEntity) as User).toUserEntity()
            else -> propertiesByName[parameter.name]?.get(this@toTeamMemberEntity)
        }
    })
}

However, when this functionality runs, the parameters object used in callBy only contains the items in the data class's generated constructor, it seems.

What am I doing wrong here to get all member properties of the *Entity classes so I can fully convert these objects without having to write this out manually?





How to get class from the method implemented in abstract class

Let's say I have an Abstract class as follows:

public abstract class Abstract{
   public void mymethod() {

   }
}

And a class implementing it:

public class Implementation extends Abstract {

}

I'm calling the mymethod from Implementation class and and inspecting it:

method.getDeclaringClass()
            .getDeclaredConstructor().newInstance();

This fails since the Declaring class is abstract so it can't be instantiated. I'm trying to figure out how to retrieve the calling class instead.





Golang - get a package and method dynamically from a string value [duplicate]

This question already has an answer here:

I come from the Java-side of things where I could easily get a class from a string and the method in the class also from a string using reflection.

I'd like to do the same thing in golang and from the looks of the specification on golang, I won't be able to do the same thing:

Essentially I want to do:

// keep in mind this is pseudo-code
func Get(className string, methodName string, parameters ...interface{}) {
  class, err := reflect.GetType(className)
  // ... typical error checking

  method, err = reflect.GetMethod(class, "methodName")
  // ... typical error checking

  method.Call(parameters)
}

I have a configuration file which may have many implementations for a particular interface. In it, I specify the type and method it should use to load and create the object.

All of the reflect code I saw was referencing having the interface upfront, ie. not from a string.

Is this possible?





Is the there a Way to Create a Constructor via Reflection that calls a Base Constructor. Specifically Entity Framework DbContext

I need to be able to call the Entity Framework model constructor of my model in 2 different ways. I either pass a connection string to my class, let's call it MyDbConnection, or I pass an existing EntityConnection (DBConnection) to my context, which comes from another application.

Everything is fine and works so far.

The problem I have, is: every time I want to use this custom way of opening my context in a new project, I need to define the 2 constructors in MyDbConnection which is quite a hassle.

Like this:

public partial class MyEntityConnection : DbContext
{
    public MyEntityConnection(string con) : base(con)
    {
    }

    public MyEntityConnection(DbConnection con, bool contextOwnsConnection) : base(con, contextOwnsConnection)
    {
    }
}

Then in my own implementation I do something like this (for the string overload):

public T GetDbContext() => (T)Activator.CreateInstance(typeof(T), _connectionstring);

and here is the problem. If I forgot to create one or both constructors, this would throw an exception.

Now I do know that you can modify the EF template to autogenerate those constructors, but im Looking for a Hands-Off Way to Archive this.

Some Way to Create the Instance of my Derived Class with a Constructor, that does not exist, and that Construtor should call its Base Constructor.

If there is a better Way to Archive this, im all ears.

private T GetExistingDbContext()
{
    try
    {
        EntityConnection econ = new EntityConnection(_internalMetadataWorkspace, _internalExistingSqlConnection);
        return (T)Activator.CreateInstance(typeof(T), econ, false);
    }
    catch (MissingMethodException)
    {
    }
    catch (Exception catr)
    {
        Console.WriteLine(catr);
        throw;
    }          
}

edit: fixed the Formating..Good God...First time Posting, sorry





Trim all string properties without reflection in c#

i need to trim all string properties in various objects at runtime, for which i have used an extension method using GetValue and SetValue of Reflection class in c#.

Any other way of doing it without using reflection, as its showing up as security issue while running fortify scan.





Delegate.DynamicInvoke can't use optional parameter?

look this code please:

// this method have a optional parameter
public static void Foo(int a = 3) { }

var del = new Action<int>(Foo);

// pass Type.Missing
del.DynamicInvoke(Type.Missing);

// or
del.DynamicInvoke(new object[] { Type.Missing });

it will get exception System.ArgumentException:

System.ArgumentException: Missing parameter does not have a default value.
Parameter name: parameters
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at xxx.btnSetting_Click(Object sender, EventArgs e) in xxx\FmMain.cs:line 106

please help.





How to get target methodinfo from a delegate

There is a express x=> x.delegate += null, how to get target methodinfo from this express. I know by il file , but it's not so friendly,

anyone has any reasonable solution?

EventInfo GetTargetMethodInfo(Delegate d)
{
    EventInfo info = null;
    var ilBytes = d.Method.GetMethodBody().GetILAsByteArray();
    var callIdx = Array.IndexOf(ilBytes, (Byte)OpCodes.Ldnull.Value);
    var calledMethodEntry = Array.FindIndex(ilBytes, x => x == OpCodes.Callvirt.Value || x == OpCodes.Call.Value);
    if (callIdx > 0 && callIdx < ilBytes.Length
        && calledMethodEntry > callIdx)
    {
        var pos = calledMethodEntry + 1;
        var methodCode = (((ilBytes[pos++] | (ilBytes[pos++] << 8)) | (ilBytes[pos++] << 0x10)) | (ilBytes[pos++] << 0x18));

        var mi = d.Method.Module.ResolveMethod(methodCode);
        if (mi != null && mi.Name.StartsWith("add_"))
        {
            var evtName = mi.Name.Substring(4);
            info = mi.DeclaringType.GetEvent(evtName);
        }
    }
    return info;
}





lundi 29 juillet 2019

Use reflection to get types from dll

I'm trying to get types from a dll that contains other dll references. How can I just ignore the referenced dlls?

I am new to work with Reflection and .dll files. I want to get types existing in the dll but I get this exception "System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified." After looking in the code, I find that the used dll file references/uses other dll files which I do not have.

How can I do to just get the types inside my dll file and ignore the types inside the referenced files?

byte[] data = System.IO.File.ReadAllBytes("filePath");
Assembly assembly = Assembly.Load(data);
var types = assembly.GetTypes();

I expect that I can get the content of the dll (classes, methods, structs, etc)





Passing type as a parameter in an api that takes a generic type

I can see many similar questions, but I can't find a solution covering this case:

I have the following code:

Service.AddQuery(T => new ServiceFactory.New())
    .AddQueryType<Test>()
    .Register(T)
    .Create());


public class Test
{
    ...
}

it's not my code and it can't be changed.

Since the system has a plugin architecture, I cannot know the Test type ahead of time, so I need to do something like:

RegisterService(Type MyQueryType)
{
    Service.AddQuery(T => new ServiceFactory.New())
        .AddQueryType<MyQueryType>()
        .Register(T)
        .Create());
}

but I can't find how to make this work.

I tried to pass typeof, I tried to create an instance with Activator.CreateInstance, etc and I can't find how to make this happen.

How can this be done?





Is there a way to read top-level struct type using method defined in embedded struct? [duplicate]

This question already has an answer here:

To satisfy some interface, I need to add a method to every object, kind of like adding trait in object oriented languages.

The plan is to create base struct with such method and to embed it into other structs, which are sometimes embedded to another structs and so on.

package main

import (
    "fmt"
    "reflect"
)

type BaseStruct struct {
}

func (this BaseStruct) InterfaceMethod() {
    str := reflect.TypeOf(this).String()
    fmt.Println(fmt.Sprintf("%s", str))
}

type StructA struct {
    BaseStruct
}

func main() {
    baseStruct := BaseStruct{}
    structA := StructA{}

    baseStruct.InterfaceMethod()
    structA.InterfaceMethod()

}

Current output:

main.BaseStruct
main.BaseStruct

Desired output:

main.BaseStruct
main.StructA 

Is there any way to check if struct is embedded in other struct, traverse through them up the top and read top-level struct name?

Go playground link: https://play.golang.org/p/794lneEtByS





dimanche 28 juillet 2019

Java Servlet reflection gridlock

I've been working with Java servlets and noticed something peculiar. To my knowledge, servlet communication with an associated .jsp file is established via reflection. Reflection is also leveraged for value-retrieval from the server side.

With that in mind, I came across an interesting problem in the following code:

protected void doPost(HttpServletRequest request, HttpServletResponse 
    response) throws ServletException, IOException {

    response.setContentType("text/html");

    String url = "/Display.jsp";

    CSVFileOperations csvfo = new CSVFileOperations();

    String header = csvfo.getHeaders().remove();
    System.out.println(header);

    request.setAttribute("header", header);

    request.getServletContext().getRequestDispatcher(url).forward(request, 
    response);

In particular, this line:

request.setAttribute("header", header);

I set both the String identifier and the variable name as the same. When I call this variable in my .jsp file via ${header}, I get the following garbage output:

{accept-language=en-US, ua-cpu=AMD64, 
cookie=JSESSIONID=1E0C2784352A46D6EFDE0F8A522F4, host=localhost:8080, 
connection=Keep-Alive, cache-control=no-cache, accept-encoding=gzip, 
deflate, accept=image/gif, image/jpeg, image/pjpeg, application/x-ms- 
application, application/xaml+xml, application/x-ms-xbap, */*, user- 
agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; Trident/7.0; rv:11.0) like 
Gecko}

However, when I change the String identifier from "header" to "head" and call ${head} in the .jsp page, I get the expected output.

My question is, what is going on here?





Swift Mirror Children collection empty when reflecting a type

I am trying to get a list of all properties on a struct.

I used this code:

struct MyBanana {
    var b: String?
}

Mirror(reflecting: MyBanana.self).children.isEmpty // returns true

Why is my .children collection empty?

I need to be able to get these from a type rather than an instance.





samedi 27 juillet 2019

How to get the annotation above the annotation

I added an annotation to the method, and there are other annotations in this annotation. When I try to get the annotation above by the method, unfortunately, the return is always null. I want to know why?

This is the method I defined

@ApiTest
  public void add() {
  }

This is the annotation I defined.

@ValueName("hello word")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiTest {

}
////////////////////////////////////////////////////////
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ValueName {
  String value() default "";
}

The result always returns null when I try to get @ValueName

Class<?> testApi = Class.forName("com.huawei.netty.TestApi");
    Method add = testApi.getMethod("add", null);
    ApiTest apiTest = add.getDeclaredAnnotation(ApiTest.class);
    ValueName valueName = apiTest.getClass().getDeclaredAnnotation(ValueName.class);
    if (valueName != null) {
      System.out.println(valueName.annotationType());
    }

But this way can be obtained

Class<?> apiTest = Class.forName("com.huawei.netty.ApiTest");
    ValueName valueName = apiTest.getDeclaredAnnotation(ValueName.class);
    if (valueName != null) {
      System.out.println(valueName.value());
    }

Can I know why this is?





.NET Core DI, injecting runtime generated class

In a .NET core application I'm using Microsoft's dependency container to register dependencies.

I want to know if it is possible to inject a derived type generated at runtime, even if the registration is that of the base type.

so

If I have something like this

pulic interface I
{
}

public class C1 : I
{
}

and the registration

sercices.AddSCoped<I, C1>();

when used

public class SomeCaller
{
     public SomeCaller(I instance) { } 
}

instead of injecting a C1 instance, I would like to inject a C1Proxy instance which was runtime generated.

Not looking to use an existing solution when it comes to the dependency container, I want to stick with what Microsoft provides.





invoke an event of injected class

I'm trying to build an infrastructure which by reflection - provides the needed objects. so far things works good, except for a case where registration to event of an injected service did not work well, and I can't invoke this event. some code: the infrastructure where the instantiation occurs:

 public ViewModelBase CreateWidget(string viewModelName)
    {
        List<object> args = new List<object>();
        Type viewModelType = widgetTypes.FirstOrDefault(type => type.Name == viewModelName);
        var ctors = viewModelType.GetConstructors();
        if (ctors == null || ctors.Count() < 1)
        {
            return null;
        }

        var ctor = ctors.FirstOrDefault();

        //Get the constructor arguments and instantiate the services (for injection)
        foreach (var param in ctor.GetParameters())
        {
            //Get the constructor's argument
            Type objectType = param.ParameterType;
            var descendantType = servicesTypes.FirstOrDefault(p => objectType.IsAssignableFrom(p));
            Assembly businessAssembly = descendantType.Assembly;

            //instantiate the services
            object service = GetInstance(businessAssembly, descendantType, null);
            args.Add(service);
        }

        Assembly assem = viewModelType.Assembly;
        ViewModelBase viewModel = null;

        //instantiate a class and injecting it the service
        object viewModelObj = GetInstance(assem, viewModelType, args.ToArray());
        viewModel = (ViewModelBase)viewModelObj;

        viewModel.RegisterToServicesEvents();

        return viewModel;
    }

    private object GetInstance(Assembly assembly, Type objectType, object[] arguments)
    {
        try
        {
            return assembly.CreateInstance(objectType.FullName, true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
         BindingFlags.CreateInstance | BindingFlags.InvokeMethod, null, arguments, CultureInfo.CurrentUICulture, null);
        }
        catch (ArgumentNullException ex)
        {
            Debug.WriteLine($"Exception has been found : {ex.Message}");
        }
        catch (MissingMethodException exm)
        {
            Debug.WriteLine($"MissingMethodException has been found : {exm.Message}");
        }

        return null;
    }

    #endregion
}

as it can be seen, after initializing the class, a method RegisterToServicesEvents is called and registring to events on the injected service is occur. and there's the problem: when tring to invoke the event on service, it looks like no object have registered to it. (I thought it probably related to late binding in the creation by reflection, but I changed the registration to the event to be only after the creation.... so) where I'm I doing wrong?





how to refelct the variable used in making an instance from an object in its name?

I have this model in django:

class Level(Model):
    level = CharField(...)

I build some instances from this model:

[Level.objects.create(level='Grade {}'.format(i)) for i in range(1, 13)]

as a result, I have 12 instances. For example:

grade_11 = Level.objects.get(level='Grade 11')

What I want to do is that I build all grade_1 to grade_12 in one line. I know it is called introspection or reflection in python but I do not know how to it. I tried this but it was not successful:

['grade_{}'.format(i) = ProgramLevel.objects.get(program_level='Grade {}'.format(i)) for i in range(1, 13)]





Kotlin data class instanciation via reflection

I am writing a small data access layer for our application connecting to MongoDB and I want to initialize queried entities to (domain model) data classes automatically using reflection

I have seen people talking about JSON deserialization to Kotlin data classes and I see why that would be an option due to MongoDB returning data in the related BSON format. However, I want to abstract over that data source.

So given a map of field names and values of arbitrary type, how can I define a function toDomain so that it takes such a map and the target class Class<T> as parameters and spits out a T as result? I am stuck because the newInstance() method invokes the (nonexistent) default constructor and the arity and types of my data class constructor arguments vary so I can't "hardcode" this information either.

Edit: I want to clarify that I do not want to know about any libraries I can simply plug into my code (except if they are open source and have a readable implementation) but instead I want to learn about the possibilities I have with reflections in this hindsight.





vendredi 26 juillet 2019

How to call DynamicMethod in DynamicMethod

How do I emit IL to call a DynamicMethod while creating a DynamicMethod?

When calling ILGenerator.Emit(OpCodes.Callvirt, myDynamicMethod); the IL that is produces results in a MissingMethodException when executed.

I reproduced the issue with this minimal code:

var dm1 = new DynamicMethod("Dm1", typeof(void), new Type[0]);
dm1.GetILGenerator().Emit(OpCodes.Ret);
var dm2 = new DynamicMethod("Dm2", typeof(void), new Type[0]);
var ilGenerator = dm2.GetILGenerator();
ilGenerator.Emit(OpCodes.Callvirt, dm1);
ilGenerator.Emit(OpCodes.Ret);

dm2.Invoke(null, new Type[0]); // exception raised here





How does reflection interact with static and instance classes?

I'm extremely new to Java, after a few hours of looking around I finally found a way to create new instances at runtime using Reflection. The issue being there is a certain amount of ambiguity in other answers and explanations of Reflection because people explain HOW to fix the problem and not WHY the fix works.

Currently the most broad reflection syntax I could find was:

Class clazz = Class.forName(fullClassPath);
Constructor<Color> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] {name});

But there are minor problems, I am having issues primarily with comprehension. In all other explanations the answers are hand-tailored to the error given. In my case while attempting to use it I apparently misunderstood the way it works.

public void createInstance() {
    String name = name; 
    try {
        Class clazz = Class.forName(fullClassPath);
        Constructor<Color> ctor = clazz.getConstructor(String.class);
        Object object = ctor.newInstance(new Object[] {name});
    } catch (Exception e) {
        }
    }

In my mind the way this would work is it would pull the current class, use it's constructor, and then rename the instance (also changing the directory name... I hope). The issue being there are some holes in that interpretation that I don't think fully mesh...

I should mention that this DOES throw an error and resorts to the catch statement rather than running the code.

I would expect reflection to require an instance method to run it properly so it can change the path for any class it is part of... but then an instance must be created PRIOR to calling the method, which would (in my mind) be unwieldy, and therefore probably incorrect.

In a static method it would have to pull from a common database, which would





How to get all methods of a Visual Studio Solution?

I need to document a complex solution for CI/CD and part of it is to build the Unit Test for all projects. My VS Solution Contains 17 projects.

enter image description here

Each of these projects contain at least 10 classes per project and most of the classes are replete with complex methods, some projects have more than a 100 classes. Most of projects are console applications, but we have an ASP MVC project too.

I'm aware that I need to prioritize the work, but in order to do it effectively, I need to have the full list of methods per class.

Does anyone know any proper technique to do it? I know that reflection could work, but it will be class by class and it might take ages too.





How to set Object's properties and its value if that Object is a property of Object that is inside of the List using Reflections

I had a similar question before, but this one will need a different solution.

I have object on my Model and object on my service.

I need to set value of Model's object property to a value of properties coming from the service's List<TicketReportPropertyEntity> if both objects' properties are the same.

This is a Model:

public class MyModel{

     public ObjectAEntity ObjectAData { get; set; }
     public ObjectBEntity ObjectBData { get; set; }
}

ObjectAEntity has a property called "SalesAmount"

This is a service:

public class MyScreenClass
{
     public List<TicketReportPropertyEntity> TicketReportPropertyEntities { get; set; } 
}

public class TicketReportPropertyEntity
{
    public decimal Amount{get;set;}
    public ReportPropertyEntity ReportProperty {get;set;}
} 

public class ReportPropertyEntity
{
    public string ReportGroup { get; set; }        
    public string PropertyName { get; set; }
}

All the properties, their values and which section(ReportGroup) on the screen they belong to (ObjectAData to the LeftSection and ObjectBData to the RightSection) I'm getting using a reflection from List<TicketReportPropertyEntity> in the following method:

private void SetValues(MyModel m, ObjectAEntity bo, object objectType)
{
    string leftSection = "LeftSection";
    string rightSection = "RightSection";


    m.ObjectAData.SaleAmount = bo.ObjectAData.SaleAmount;
    foreach (var ticketReportEntity in mol.TicketReportPropertyEntities)
    {
        var type = ticketReportEntity.GetType();
        PropertyInfo reportProperty = type.GetProperty("ReportProperty");
        PropertyInfo reportPropertyName = typeof(ReportPropertyEntity).GetProperty("PropertyName");
        PropertyInfo reportPropertyReportGroup = typeof(ReportPropertyEntity).GetProperty("ReportGroup");
        PropertyInfo amountProperty = type.GetProperty("Amount");
        ReportPropertyEntity reportPropertyValue = (ReportPropertyEntity)reportProperty.GetValue(ticketReportEntity, null);
        string reportPropertyNameValue = (string)reportPropertyName.GetValue(reportPropertyValue, null);
        decimal value = (decimal)amountProperty.GetValue(ticketReportEntity, null);


//here I need to see if Model's object has the same property as in `ReportProperty` class. 

bool has = m.TicketReportPropertyEntities.Any(element => element.ReportProperty.PropertyName.Equals(reportPropertyNameValue));

    if (has)
    {
        //need to set the value of the Model's `ObjectAEntity` property 
    }
}

How can I do something like that?





Edit method at runtime in .Net Core C#

I'm working on a unit testing framework and part of that is intercepting calls to methods. I had a prototype using pointer manipulation on the pointers in MethodBase.MethodHandle but in some cases it would stop working depending on if the debugger was attached or not and in other cases it wouldn't work with functions (had it working for Actions though).

I suspect pointer manipulation is still a possible option but I don't know the memory layout or anything.

The fallback option I came up with is having the test method call my function with the function they want to call and then I generate a dynamic method, copying the IL and altering call instructions to call my methods instead. But it's not a great solution.

I looked through tens of sources but these are the ones that got me closest:





Error in .java that cannot be resolved after changing in gradle android

App works fine till yesterday but today when I opened the project, I get error only in .java

In a class, only in .java I get error as unresolved error java.

 intent = Intent(this@UserImageActivity, UserDetailsActivity::class.java)

I used invalidate cache and restart but still I couldn't resolve the compile error.

  build.gradle (app)

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
       }

     build.gradle (AppProject)

     buildscript {
        ext.kotlin_version = '1.3.11'
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.2.1'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

build.gradle (app)

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"

enter image description here





How to execute generic method by setting double generic using reflection

I have a class and it has generic method:

   public class MyClass
   {
      public void MyMethod<T, IEntity>()
      {

      }
   }

In some places I'm executing it using reflection:

        var intType = typeof(int);
        var stringType = typeof(string);
        MethodInfo method = typeof(MyClass).GetMethod(nameof(MyClass.MyMethod));
        MethodInfo generic = method.MakeGenericMethod(intType, stringType);
        generic.Invoke(myClass, null);

It works. In some cases I need to use Action in method:

myClass.MyMethod<Action<int>, string>();

How can I do that using reflection?





jeudi 25 juillet 2019

Why is declaredFields including $change and serialVersionUID

In my android project I'm trying to loop through all the fields of a class using reflection, however, the result of declaredFields includes two unexpected fields, $change and serialVersionUID which aren't defined in the class

This is in an android project using a Kotlin data class. I've tried looking up the two fields in question and have seen that serialVersionUID seems to relate to classes which extend serialisable (https://stackoverflow.com/a/285809/8023278), the class in question doesn't implement serialisable though and I can't find any details about $change.

data class MyClass(
        @field:Json(name = "Id") var id: String
)

// then in some other class/method
MyClass::class.java.declaredFields.forEach { 
  // do something. 
  Log.d("", it.name)
}

I would expect only id to be logged however I actually get id, $change and serialVersionUID.





Deserialize JSON object to specific instance created on the fly in run time by string name of the class

Working on several RDLC, in C# VS2017, I found that I need to send specific instances of my own objects. Avoiding the struggling with a large switch, I want to know if there is some way to create an instance on the run time by the class name

I've a dummy fiddle in order to test it, but can't complete it: https://dotnetfiddle.net/eMwleG

My code until now, after a lot of test and answers from SO, from JSON Conversion to Casting types and using reflection:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Reflection;                    
public class Program
{
    public static T GetObjectAs<T>(object source, T destinationType)
   where T: class
{
     return Convert.ChangeType(source, typeof(T)) as T;
}

    public static void Main()
    {
        //From Object to string
        var nameMessage = new MessageWrapper<Name>();
        nameMessage.Message = new Name {First="Bob", Last = "Smith"};
        string serialized = JsonConvert.SerializeObject(nameMessage);

        //From String to Object
        var deserialized = JsonConvert.DeserializeObject<MessageWrapper>(serialized);
        var messageType = Type.GetType(deserialized.MessageType);

        var message = JsonConvert.DeserializeObject(Convert.ToString(deserialized.Message), messageType);

        Name myname = GetObjectAs(message, System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("Name"));

        //Name myname =  Convert.ChangeType(message,messageType) as Name;
        Console.WriteLine(myname.First);

    }
}

public class MessageWrapper<T>
{
    public string MessageType { get { return typeof(T).FullName; } }
    public T Message { get; set; }
}

public class MessageWrapper
{
    public string MessageType { get; set; }
    public object Message { get; set; }
}


public class Name
{
    public string First;
    public string Last;
}

So my question is:

How can create an specific instance of my object "Name" in run time and assign it from an objected casted by a dynamic conversion?

Please don't try to cover the logic of the example, is a dummy example to do something. I can accept answers and ideas of course, with the same spirit, take in consideration I don't "know" the class called to be casted.





JsonConvert.DeserializeObject throws exception when desalinizing json with int that doesn't fit range

My class MyData has sbyte members.

I'm using the following

var deserialized = JsonConvert.DeserializeObject<List<MyData>>(JsonStr);

Some values exceed sbyte range, for example 0xAA. As a result, exception are thrown. When I change the value to 0x1, for example, it works.

I can not touch the code of MyData. It's machine-generated. I expect use of conversion settings, override of something, use of LINQ e.t.c





Go: what is the right way to use go-ini's mapTo function?

Background

I'm trying to use go-fed's apcore framework to build a federated app. I have implemented the apcore.Application interface but I'm stuck during the loading of the configuration.

The server responds with panic: reflect: call of reflect.Value.Type on zero Value when trying to map the configuration loaded from config.ini to the apcore configuration struct.

This happens here:

func loadConfigFile(filename string, a Application, debug bool) (c *config, err error) {
    InfoLogger.Infof("Loading config file: %s", filename)
    var cfg *ini.File
    cfg, err = ini.Load(filename)
    if err != nil {
        return
    }
    err = cfg.MapTo(c)
    if err != nil {
        return
    }
.
.
.

where it clearly just uses an uninitialized *config pointer. This led me to believe this has nothing to do with the code I've written (an implementation of Application) which has not been yet used here.

The question

I decided to write a very simple usecase of MapTo to check if it works as I expect it to:

package main

import (
    "fmt"
    "gopkg.in/ini.v1"
)

type Config struct {
    Name      string `ini:"NAME"`
    Male      bool
    Age       int `comment:"Author's age"`
    GPA       float64
}

func main() {
    var cfg *ini.File
    var err error
    cfg, err = ini.Load("config.ini")
    var c *Config
    // c := &Config{ Name: "test", Male: true, Age: 13, GPA: 4.5 }
    // c := new(Config)
    fmt.Println(c);
    err = cfg.MapTo(c)
    fmt.Println(err.Error())
}

This also returns panic: reflect: call of reflect.Value.Type on zero Value. Neither passing a Config literal works (it then complains that it cannot map to non-pointer struct), nor an initialized pointer (signal SIGSEGV: segmentation violation).

This is the function declaration

func (s *Section) mapTo(val reflect.Value, isStrict bool) error {

What does it require as input and why does the go-ini library use it this way if it fails?

(I also tried with older go-ini just in case it's a recent bug)





Using C# Reflection, how to get Object's properties and their values if that Object is a property of Object that is inside of the List

I need to grab the value of a property of an ObjectB, which is a Property of ObjectA and ObjectA is inside of a List<ObjectA>

I browsed through some examplse, but could not find exactly what I need.

Here is what I'm looking for:

I have a class MyScreenClass, that has a List<TicketReportPropertyEntity>:

public class MyScreenClass
{
     public List<TicketReportPropertyEntity> TicketReportPropertyEntities{ get; set; } 
}

This is TicketReportPropertyEntity class that has another class which property I need to work with:

public class TicketReportPropertyEntity
{
    public decimal Amount{get;set;}
    public ReportPropertyEntity ReportProperty {get;set;}
} 

This is ReportPropertyEntity class:

public class ReportPropertyEntity
{
    public string PropertyName { get; set; }
}

What I need to do, is for each TicketReportPropertyEntity to get Amount from TicketReportPropertyEntity and PropertyName from ReportPropertyEntity.

The purpose is I need to compare the PropertyName with a given property and set the value to an Amount

So far, I only came up with the following:

foreach (var ticketReportEntity in mol.TicketReportPropertyEntities)
{
   PropertyInfo propertyInfo1 = ticketReportEntity.GetType().GetProperty("ReportProperty");
           //here I need to do all the logic
}

What is the solution?





Strange behavior of asSubclass method

Now i'm playing around with reflection and encounter with not quite clear behavior for me.

        Class<? extends List> listClass = ArrayList.class.asSubclass(List.class);

        System.out.println(listClass.isInstance(ArrayList.class));  //print false
        System.out.println(listClass.getSimpleName());// print ArrayList

Sorry if my question is stupid and isn't new but i can't understand why

listClass.isInstance(ArrayList.class) return false, although

listClass.getSimpleName() return ArrayList

Can someone explain this behavior? Thanks in advance.





How to recognize which methods are getters and setters?

I am trying to use reflection to get all class methods. I want to prepare an algorithm that will recognize which methods are getters and setters.

So, as you see I am printing each getter in the format: {name} will return {Return Type}. I am trying to print all of the setters in the format: {name} will set field of {Parameter Type}, but I don't know how to get the Parameter Type.

public string CollectGettersAndSetters(string className)
{
    Type classType = Type.GetType(className);

    MethodInfo[] getters = classType
        .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
        .Where(m => m.Name.StartsWith("get"))
        .ToArray();

    MethodInfo[] setters = classType
        .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
        .Where(m => m.Name.StartsWith("set"))
        .ToArray();

    StringBuilder sb = new StringBuilder();

    foreach (MethodInfo getter in getters)
    {
        sb.AppendLine($"{getter.Name} will return {getter.ReturnType}");
    }

    foreach (MethodInfo setter in setters)
    {
        sb.AppendLine($"{setter.Name} will set field of {?}");
    }

    return sb.ToString().TrimEnd();
}

An example of class for which I will use the method:

public class Hacker
{
    public string username = "securityGod82";
    private string password = "mySuperSecretPassw0rd";

    public string Password
    {
        get => this.password;
        set => this.password = value;
    }

    private int Id { get; set; }

    public double BankAccountBalance { get; private set; }

    public void DownloadAllBankAccountsInTheWorld()
    {
    }
}

The expected output is:

get_Password will return System.String
get_Id will return System.Int32
get_BankAccountBalance will return System.Double
set_Password will set field of System.String
set_Id will set field of System.Int32
set_BankAccountBalance will set field of System.Double

Thank you in advance!





Will swift mirror keep the property order?

We can iterate with (name, value) tuple, but are they coming the same order as we defined it? Let's go with the

struct Book {
    let title: String
    let author: String?
    let published: Date
    let numberOfPages: Int
    let chapterCount: Int?
    let genres: [String]
}

And the result is:

// title: String = 'Harry Potter'
// author: Optional<String> = 'Optional("J.K. Rowling")'
// published: Date = '2016-10-02 19:17:43 +0000'
// numberOfPages: Int = '450'
// chapterCount: Optional<Int> = 'Optional(19)'
// genres: Array<String> = '["Fantasy", "Best books ever"]'

Check the order: it's very same. Can we be sure, that it's the same? (Code snippets are from https://makeitnew.io/reflection-in-swift-68a06ba0cf0e)





Scala reflection to cast using return type of method at runtime

I am using reflection in scala and i want to generalize the code to cast object to return type of another method which is identified at runtime using reflection

I have tried to get return type of method using reflection but not able to use this in asInstance[] cast operation.

import java.lang.reflect.Modifier
object Test5 {

  def main(args: Array[String]): Unit = {
    val runtimeClass = Class.forName("ConvertToUpper")
    invokeRuntimeMethod(runtimeClass, "toUpper")
  }

  def invokeRuntimeMethod(runtimeClass: Class[_], methodName: String): Unit = {
    val runtimeMethod = runtimeClass.getDeclaredMethod(methodName)
    var runtimeClsConstructor: java.lang.reflect.Constructor[_] = null
    if (!Modifier.isStatic(runtimeMethod.getModifiers)) {
      runtimeClsConstructor = runtimeClass.getDeclaredConstructor()
      runtimeClsConstructor.setAccessible(true)
    }
    println("Return Type =>" + runtimeMethod.getReturnType)
    println("Generic Return Type => " + runtimeMethod.getGenericReturnType)

    runtimeMethod.setAccessible(true)
    val runtimeObj = if (runtimeClsConstructor != null) runtimeClsConstructor.newInstance()
    else runtimeClsConstructor

    val runtimeFunction = runtimeMethod.invoke(runtimeObj).asInstanceOf[Function1[String, String]]
    println("output => " + runtimeFunction("test"))

  }
}

Here i want to generalize the function so that i don't need to write Function1. I am already getting return type i.e. Generic Return Type => scala.Function1. How can i use this return type in asInstanceOf directly instead of hard coding Function1 like runtimeMethod.invoke(runtimeObj).asInstanceOf[runtimeMethod.getGenericReturnType]





BeanPropertyRowMapper cache problem on Tomcat

I am using my custom row mapper extended from BeanPropertyRowMapper to override underscoreName method. It was working well. I added new fields to DTO class and deployed to Tomcat again. But it couldn't map new fields. In BeanPropertyRowMapper's initialize method it is using BeanUtils.getPropertyDescriptors(mappedClass). I think the problem is due to not updated cache on deploy.

I tried to restart tomcat but it didn't work.

@Slf4j
public class ColumnRowMapper<T> extends BeanPropertyRowMapper<T> {

  private ColumnRowMapper(final Class<T> mappedClass) {
    super(mappedClass);
  }

  @Override
  protected String underscoreName(final String name) {
    Field declaredField = getField(getMappedClass(), name);
    String columnName = getColumnName(declaredField);
    return columnName == null ? super.underscoreName(name) : columnName.toLowerCase();
  }

  private Field getField(Class<?> clazz, String name) {
    if (clazz == null) {
      return null;
    }
    Field field = null;
    try {
      field = clazz.getDeclaredField(name);
    } catch (Exception e) {
      field = getField(clazz.getSuperclass(), name);
    }
    if (field == null) {
      log.warn("Ups, field «{}» not found in «{}».", name, clazz);
    }
    return field;
  }

  private String getColumnName(Field declaredField) {
    Column annotation;
    String columnName;
    if (declaredField == null || (annotation = declaredField.getAnnotation(Column.class)) == null
        || StringUtils.isEmpty(columnName = annotation.name())) {
      return null;
    }
    return columnName;
  }

  public static <T> BeanPropertyRowMapper<T> newInstance(final Class<T> mappedClass) {
    return new ColumnRowMapper<>(mappedClass);
  }

}





How do I use reflection to configure all implementations of interface for DI as IOptions<>?

Introduction

I'm using IOptions<> in ASP to provide configuration to services. Currently I have to setup each POCO individually. I would like to do this in a generic way.

I would like to use some sort of reflection to automaticly configure all POCO's that are used for configuration injection with IOptions. Thus avoiding calling the services.Configure<Poco>() for each class.

The working setup

My appsettings.json file.

{
  "DemoOption": {
    "OptionOne": "hello",
    "OptionTwo": "world"
  }
}

POCO for configuration section:

public class DemoOption
{
    public string OptionOne { get; set; }
    public string OptionTwo { get; set; }
}

Enables me to do this:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<DemoOption>(configuration.GetSection(nameof(DemoOption)));
}

And use it like this:

public class MyService
{
    public IOptions<DemoOptions> _options { get; set; }

    public MyService(IOptions<DemoOptions> options)
    {
        _options = options;
    }
}

What I've got this far

To use reflection I create and add an IOption interface to my POCO class:

public class DemoOption : IOption // Added empty IOption interface
{
    public string OptionOne { get; set; }
    public string OptionTwo { get; set; }
}

This is where I'm stuck. I've gotten all the implementations of the IOptions interface, but I can't figure out how to call the services.Configure() method.

public void ConfigureServices(IServiceCollection services)
{
    // This actually works and finds all implementations.
    var options = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(x => x.GetTypes())
        .Where(x => typeof(IOption).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
        .Select(x => x).ToList();

    // This does not work
    foreach (var o in options)
    {
        // What should I write here?
        services.Configure<o>(configuration.GetSection(nameof(o)));
    }
}

All help appriciated.





How I can implement own annotation in Java similar to Lombok's annotations

Is it possibile to create own annotation that will be visible at compile time like in Lombok lib?

Let's imagine that class has 100 buttons as fields and 100 corresponding click methods. That makes the class pretty large.

public class MainPage {

    private Button logo;
    private Button importImage;
    private Button switcher;
    // ... Buttons

    public void clickOnLogo() {
        Clicker.click(logo);
    }

    public void clickOnImportImage() {
        Clicker.click(importImage);
    }

    public void clickOnSwitcher() {
        Clicker.click(switcher);
    }
    // ... Corresponding click methods

}

I`d like to create some annotation to apply it for each field or for class instead of writing methods.

@Clickable
public class MainPage {

    private Button logo;
    private Button importImage;
    private Button switcher;

}

public class Runner {

    public static void main(String[] args) {
        // Some code initializing the main page.........
        MainPage page = new MainPage();
        page.clickOnLogo();
        page.clickOnImportImage();
        page.clickOnSwitcher();
    }

}





mercredi 24 juillet 2019

Why does Activator.CreateInstance() for a Generic List Produce a Non-Matching Type?

The following code example is just for illustration purposes. I realize its not practical, but my practical use case is much more complex. I'm trying to keep it simple for demonstration.

Assume that the passed in argument "collection" contains a List of System.String.

public dynamic DoopList(dynamic collection)
{
   Type collectionType = collection.GetType();

   Type[] args = iCollection.GetGenericArguments();

   Type listType = typeof(List<>).MakeGenericType(genericArg);

   if(collectionType == listType)
       return Activator.CreateInstance(listType);
   else
       return null;
}

Now I would THINK that DoopList would return exactly the same Type as collection. Instead, you get a slightly different type because Activator.CreateInstance() returns a slight variation.

When I pass in a collection of type: System.Collections.Generic.List`1[System.String]

...the if condition evaluates to true, and the function returns an object of type: System.Collections.Generic.List<String>

Well that's a problem, because then I can't assign the result to another variable that expects System.Collections.Generic.List`1[System.String].

I'm pretty sure what's going on here has something to do with nature of generics, but I really don't understand it.

What is the difference between Generic.List`1[System.String] and Generic.List<string>?

And more importantly, why does Activator.CreateInstance() create a Generic.List<string> instead of a Generic.List`1[System.String] and how do I fix the problem so I can get the same type as the input collection?





How can I load "assembly extern" references using AssemblyLoadContext?

I am building a simple plugin architecture in .NET Core 3.0. I have a solution with two projects: Plugin and WpfApp. Here is the version of the .NET Core 3.0 SDK I have installed:

PS > dotnet --version
3.0.100-preview7-012821

Plugin

The Plugin project is a class library project targeting .NET Standard 2.0. It references the System.Management NuGet package version 4.5.0 and uses classes from that package. The project compiles, of course. Here is the relevant IL from the assembly showing the assembly extern reference:

// Metadata version: v4.0.30319
.assembly extern netstandard
{
  .publickeytoken = (CC 7B 13 FF CD 2D DD 51 )                         // .{...-.Q
  .ver 2:0:0:0
}
.assembly extern System.Management
{
  .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )                         // .?_....:
  .ver 4:0:0:0
}

WpfApp

The WpfApp project is a WPF project targeting .NET Core 3.0. I configured the project to depend on Plugin using Solution Explorer's Project Dependencies feature, since WpfApp doesn't directly reference Plugin. This ensures Plugin always builds before WpfApp.

WpfApp references the System.Runtime.Loader NuGet package version 4.3.0 in order to use its AssemblyLoadContext class. My MainWindow window loads the Plugin project DLL using AssemblyLoadContext.LoadAssemblyFromFile. WpfApp then instantiates a MyPlugin class from Plugin and attempts to invoke the Invoke method. Invoke instantiates classes from System.Management:

Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"C:\Solutions\Plugins\Plugin\bin\Debug\netstandard2.0\Plugin.dll");
object instance = assembly.CreateInstance("Plugin.MyPlugin");

instance.GetType().GetMethod("Invoke").Invoke(instance, new object[0]);

As soon as Invoke attempts to do this, an exception is thrown:

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

Inner exception:

FileNotFoundException: Could not load file or assembly 'System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

What's going on here?

I expected AssemblyLoadContext to load all these system references, but it seems I was incorrect. As far as I can tell, referencing the NuGet package does not actually copy DLLs to Plugin's output directory but merely causes the above assembly extern IL to be generated. This is breaking my plugin architecture because I cannot possibly know all the external .NET Core 3.0 SDK assemblies that all plugins might reference. I'd understand if it were trying to load third-party references but these are NuGet packages representing DLLs included in the .NET Core 3.0 SDK. In my case, I can guarantee they'll be on the system.

Am I doing something wrong? How can I get AssemblyLoadContext to load these external references? Alternatively, is there any other way of getting this to work aside from copying System.Management.dll (which I do not view as a viable solution)?





How to call projectwide properties using Reflection?

I am building a newsfeed system for a game, and I have a file which contains various string messages that the system reads in to show them on screen.

Strings like that are not the problem: "Welcome to Trash Island"

But I would like to add some dynamic text that includes some specific variables from classes or non-void functions that return their result to the defined position of the message:

Example: "Time: [SHOW CURRENT TIME]" should give "Time: 10:23pm"

I think it could be good enough to use tags that mark the code. To implement the format of the example above I have come up with this:

"Time: < code=UIManager.ToTime(DayManager.instance.dayTime)/>"

//Note: daytime is a float value and ToTime returns a time formatted string

This is my approach, but of course not working:

string msg = messages [_index];
string prefix = "";
string subfix = "";
string code = "";
if (msg.Contains ("<code=")) {
    int start = msg.IndexOf ("<code=")
    prefix = msg.Substring (0, start);
    start += 6;
    end = msg.IndexOf ("/>");
    code = msg.Substring (start, end - start);
    sufix = msg.Substring (end+2, msg.Length-1);
    Debug.Log ("Function found: " + code);
    string codeReturnValue = //DO MAGIC REFLECTION WITH "code" 
    text_message.text = prefix + codeReturnValue + subfix;
} else { 
    text_message.text = msg;
}

But how would I turn "code" to an actual call using reflection?

I think this is not possible, but how would I manage something like this without having to create tons of hard coded functions and instead gather all information based of the message-string?





Is it possible to get condition of predicate?

I wonder if it is possible to fetch Predicate's condition, for example with reflection. For example I have following Predicate:

Predicate<TextInputControl> isTextFieldEmpty = field -> field.getText().isEmpty();


My intention is to get:

field -> field.getText().isEmpty()

Preferably as String.





Reflection : Get fieldName and value

I have class object inside another class.

class A {
  private int id;
}

class B {
private String name;
private A classA;
}

For simple class, I am able to get the fields value and name as below :

MyClass ch = new MyClass();

Class<?> clazz = ch.getClass();

           for(Field field : clazz.getDeclaredFields()) {
               field.setAccessible(true);
               System.out.println(field.getName() + " : " + field.get(ch));

       }

How can I use reflection to get the field name and value when a class is present as class property?





Generating code in existing classes in runtime (Java)

I have already created an empty class SimpleClass. How can I generate some code in this class in runtime and recompile the class to be able to use that code?

public class SimpleClass {}

I've found the solution with generating whole class with it's content using custom ClassLoader and javax.tools API. But is there any for existing class?

public class SimpleClass {

    //Generated code in runtime
    public void method() {
       System.out.println("Generated method");
    }

}





how to fetch webapi controller method params values from an ActionFilterAttribute using reflection

is there a way of getting the current values of passed parameters to a method using reflection?

(just for clarification - i'm not need it for debugging,

i want to fetch webapi controller method params values from an ActionFilterAttribute).





Replacing an annotation with another annotation during compile time in Spring?

I am using Swagger annotations over my controller parameters. So, I end up with annotations like @ApiParam(name="default name", value="this is a default value"). I think these is quite verbose. I would like to change it to something like @Foo. I want to know if there's a way to replace @Foo with @ApiParam during compile time. Also, since I am using Spring, I think I have to consider the annotation processing order in Spring, as well. I mean I shouldn't replace @ApiParam with @Foo after Swagger or Spring picks it up. Is there any way to do this?

I know I have to show what I have already tried, but I have no clue where to even start.

Also, the question is not related to Swagger, it is just an example. I want to replace one annotation with another during compile time, so that the one picked up by Spring won't be the one I have put on the source code, but the one I have replaced.





Subscribe to whatever method is being executed

In my app I'm creating an auditing package that obtains various information, one such type of information should provide different information regarding what method is executed (time it took to execute, method name, method class, assembly, etc).

I'm not looking to use an existing package or framework, but to create my own.

I can imagine that this is a complicated thing to do, but I'm looking for some pointers to get me started .





mardi 23 juillet 2019

Find a string in a list of strings in c# with reflection

List<string> typesList = new List<string>();
typesList.Add("product");
typesList.Add("valueType");
typesList.Add("categoryType");

foreach (var prop in someType.GetProperties())
{
    string filterValue = Filter.SecondStringByProp(prop, filterList, "_");//this return `valueType`

    bool wtf1 = typesList.Any(x => x == prop.Name.ToLower());
    bool wtf2 = typesList.Contains(prop.Name.ToLower());
    var wtf3 = typesList.Where(x => x == prop.Name.ToLower()).FirstOrDefault();
    bool wtf4 = string.IsNullOrEmpty(typesList.Where(x => x == prop.Name.ToLower()).FirstOrDefault());
    bool wtf5 = !string.IsNullOrEmpty(typesList.Where(x => x == prop.Name.ToLower()).FirstOrDefault());
    bool wtf6 = typesList.Any(s => s.Contains(prop.Name.ToLower()));
}

answer that always work but not now!

I do not understand why so many different ways that I think should work DO NOT WORK - to return bool

the above code is checking if prop.Name.ToLower() which is valueType is equal to element from collection typesList (valueType)

wtf1 and wtf2 - just for testing purpose and curiosity wtf4 and wtf5 - this just return the expected value wtf6 - wtf why return false?!





Is it possible to get all methods of a class, in the correct order? [duplicate]

This question already has an answer here:

I'm trying to retrieve a list of methods inside a specific class, but it has to be in order. The second part is where I'm stuck and uncertain if it's even possible.

This is the method that retrieves the list:

public static ArrayList<Method> getAllMethods (MyClass myClass) {
    ArrayList<Method> methods = new ArrayList<Method>();
    Class c = myClass.getClass();
    while (c != Object.class) {
        Collections.addAll(methods, ClassReflection.getDeclaredMethods(c));
        c = c.getSuperclass();
    }
    return methods;
}

The result is that the list contains all the methods in a what seems to be random order. For my program that's very inconvenient. Is it possible to do this in a simple way? The only way I thought of was adding annotations and order each method by giving it a number. However, that seems like a lot of hassle for what I'm trying to achieve and I don't want to do it this way.

EDIT: I use the retrieved methods to get the annotations that belong to them. Next I display these annotations on screen in my game, because the methods are basically in-game commands. The commands are written in a logical order and some commands are grouped together so they need to be displayed next to each other and in the correct order. Here is how I display the annotation values:

@Command(description = "Shows all commands and their usages")
public void help() {
    for(Method command : Util.getAllMethods(this)) {
        Annotation anno = command.getDeclaredAnnotation(Command.class);
        if(command.isAnnotationPresent(Command.class)){
            Command cmd = anno.getAnnotation(Command.class);
            console.log(command.getName() + " " + cmd.param() + " : " + cmd.description());
        }
    }
}





Why are ParameterInfo and MemberInfo causing an AmbigousMatchException?

According to Microsoft Metadata, ParameterInfo is:

namespace System.Reflection
{
  //
  // Summary:
  //   Discovers the attributes of a parameter and provides access to parameter
  //   metadata.
  public class ParameterInfo : ICustomAttributeProvider, IObjectReference
  // ....
}

and MemberInfo is:

namespace System.Reflection
{
  //
  // Summary:
  //   Obtains information about the attributes of a member and provides access to member
  //   metadata.
  public abstract class MemberInfo : ICustomAttributeProvider
  // ...
}

So I'm not sure why the following code would throw an AmbiguousMatchException:

DotNetFiddle Example.

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var pi = typeof(object).GetMethod("Equals").GetParameters()[0];
        Test(pi);
    }

    private static void Test(MemberInfo mi)
    {
    }

    private static void Test(ParameterInfo pi)
    {
    }
}

result:

Unhandled Exception: System.Reflection.AmbiguousMatchException: Ambiguous match found.

at System.RuntimeType.GetMethodImplCommon(String name, Int32 genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers)

at System.RuntimeType.GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers)

at System.Type.GetMethod(String name, BindingFlags bindingAttr)

at Program.Main()





Introspecting _ENV from coroutines

This question is motivated by exercise 25.1 (p. 264) of Programming in Lua (4th ed.). That exercise reads as follows:

Exercise 25.1: Adapt getvarvalue (Listing 25.1) to work with different coroutines (like the functions from the debug library).

The function getvarvalue that the exercise refers to is copied verbatim below.

-- Listing 25.1 (p. 256) of *Programming in Lua* (4th ed.)

function original_getvarvalue (name, level, isenv)
  local value
  local found = false

  level = (level or 1) + 1

  -- try local variables
  for i = 1, math.huge do
    local n, v = debug.getlocal(level, i)
    if not n then break end
    if n == name then
      value = v
      found = true
    end
  end
  if found then return "local", value end

  -- try non-local variables
  local func = debug.getinfo(level, "f").func
  for i = 1, math.huge do
    local n, v = debug.getupvalue(func, i)
    if not n then break end
    if n == name then return "upvalue", v end
  end

  if isenv then return "noenv" end   -- avoid loop

  -- not found; get value from the environment
  local _, env = getvarvalue("_ENV", level, true)
  if env then
    return "global", env[name]
  else        -- no _ENV available
    return "noenv"
  end

end

Below is my enhanced version of this function, which implements the additional functionality specified in the exercise. This version accepts an optional thread parameter, expected to be a coroutine. The only differences between this enhanced version and the original are:

  1. the handling of the additional optional parameter;
  2. the special setting of the level depending on whether the thread parameter is the same as the running coroutine or not; and
  3. the passing of the thread argument in the calls to debug.getlocal and debug.getinfo, and in the recursive call.

(I have marked these differences in the source code through numbered comments.)

function enhanced_getvarvalue (thread, name, level, isenv)
  -- 1
  if type(thread) ~= "thread" then
    -- (thread, name,  level, isenv)
    -- (name,   level, isenv)
    isenv = level
    level = name
    name = thread
    thread = coroutine.running()
  end

  local value
  local found = false

  -- 2
  level = level or 1
  if thread == coroutine.running() then
    level = level + 1
  end

  -- try local variables
  for i = 1, math.huge do
    local n, v = debug.getlocal(thread, level, i) -- 3
    if not n then break end
    if n == name then
      value = v
      found = true
    end
  end
  if found then return "local", value end

  -- try non-local variables
  local func = debug.getinfo(thread, level, "f").func  -- 3
  for i = 1, math.huge do
    local n, v = debug.getupvalue(func, i)
    if not n then break end
    if n == name then return "upvalue", v end
  end

  if isenv then return "noenv" end   -- avoid loop

  -- not found; get value from the environment
  local _, env = enhanced_getvarvalue(thread, "_ENV", level, true)  -- 3
  if env then
    return "global", env[name]
  else
    return "noenv"
  end

end

This function works reasonably well, but I have found one strange situation1 where it fails. The function make_nasty below generates a coroutine for which getvarvalue_enhanced fails to find an _ENV variable; i.e. it returns "noenv". (The function that serves as the basis for nasty is the closure outer_closure, which in turn invokes the closure inner_closure. It is inner_closure that then yields.)

function make_nasty ()
  local function inner_closure () coroutine.yield() end
  local function outer_closure ()
    inner_closure()
  end

  local thread = coroutine.create(outer_closure)
  coroutine.resume(thread)
  return thread
end

nasty = make_nasty()
print(enhanced_getvarvalue(nasty, "_ENV", 2))
-- noenv

In contrast, the almost identical function make_nice produces a coroutine for which getvarvalue_enhanced succeeds in finding an _ENV variable.

function make_nice ()
  local function inner_closure () coroutine.yield() end
  local function outer_closure ()
    local _ = one_very_much_non_existent_global_variable  -- only difference!
    inner_closure()
  end

  local thread = coroutine.create(outer_closure)
  coroutine.resume(thread)
  return thread
end

nice = make_nice()
print(enhanced_getvarvalue(nice, "_ENV", 2))
-- upvalue  table: 0x558a2633c930

The only difference between make_nasty and make_nice is that, in the latter, the closure outer_closure references a non-existent global variable (and does nothing with it).

Q: How can I modify getvarvalue_enhanced so that it is able to locate _ENV for nasty, the way it does for nice?


1 I am sure that someone with a better understanding of what is going on in this example will be able to come up with a less convoluted way to elicit the same behavior. The example I present here is the most minimal form I can come up with for the situation I found by accident.





Getting object property value in non public members

In my cookie collection, I need to retrieve this value and I realize that I can use reflection to do it. After seeking some references from Google, I keep getting null from my code. Anyone know where's my problem?

var cookielist = 
allCookies.GetType().GetField("m_list[0]", BindingFlags.NonPublic | BindingFlags.Instance);

enter image description here





lundi 22 juillet 2019

Is there a way to access a class's members where when acessing you use a string instead of class name

Im looking to use some reflection to access all the members in a class and get their values. This is the class's. I always initialize the "Championsids" class. (I know there is a lot of code but its quite straight forward).

        public class ChampionIds
        {
            public string type;
            public string format;
            public string version;
            public Data data;
        }

        public class Data
        {
            public Champions Aatrox;
            public Champions Ahri;
            public Champions Akali;
            public Champions Alistar;
            public Champions Amumu;
            public Champions Anivia;
            public Champions Annie;
            public Champions Ashe;
            public Champions AurelionSol;
            public Champions Azir;
            public Champions Bard;
            public Champions Blitzcrank;
            public Champions Brand;
            public Champions Braum;
            public Champions Caitlyn;
            public Champions Camille;
            public Champions Cassiopeia;
            public Champions Chogath;
            public Champions Corki;
            public Champions Darius;
            public Champions Diana;
            public Champions Draven;
            public Champions DrMundo;
            public Champions Ekko;
            public Champions Elise;
            public Champions Evelynn;
            public Champions Ezreal;
            public Champions FiddleSticks;
            public Champions Fiora;
            public Champions Fizz;
            public Champions Galio;
            public Champions Gangplank;
            public Champions Garen;
            public Champions Gnar;
            public Champions Gragas;
            public Champions Graves;
            public Champions Hecarim;
            public Champions Heimerdinger;
            public Champions Illaoi;
            public Champions Irelia;
            public Champions Ivern;
            public Champions Janna;
            public Champions JarvanIV;
            public Champions Jax;
            public Champions Jayce;
            public Champions Jhin;
            public Champions Jinx;
            public Champions Kalista;
            public Champions Karma;
            public Champions Karthus;
            public Champions Kassadin;
            public Champions Katarina;
            public Champions Kayle;
            public Champions Kennen;
            public Champions Khazix;
            public Champions Kindred;
            public Champions Kled;
            public Champions KogMaw;
            public Champions Leblanc;
            public Champions LeeSin;
            public Champions Leona;
            public Champions Lissandra;
            public Champions Lucian;
            public Champions Lulu;
            public Champions Lux;
            public Champions Malphite;
            public Champions Malzahar;
            public Champions Maokai;
            public Champions MasterYi;
            public Champions MissFortune;
            public Champions MonkeyKing;
            public Champions Mordekaiser;
            public Champions Morgana;
            public Champions Nami;
            public Champions Nasus;
            public Champions Nautilus;
            public Champions Nidalee;
            public Champions Nocturne;
            public Champions Nunu;
            public Champions Olaf;
            public Champions Orianna;
            public Champions Pantheon;
            public Champions Poppy;
            public Champions Quinn;
            public Champions Rammus;
            public Champions RekSai;
            public Champions Renekton;
            public Champions Rengar;
            public Champions Riven;
            public Champions Rumble;
            public Champions Ryze;
            public Champions Sejuani;
            public Champions Shaco;
            public Champions Shen;
            public Champions Shyvana;
            public Champions Singed;
            public Champions Sion;
            public Champions Sivir;
            public Champions Skarner;
            public Champions Sona;
            public Champions Soraka;
            public Champions Swain;
            public Champions Syndra;
            public Champions TahmKench;
            public Champions Taliyah;
            public Champions Talon;
            public Champions Taric;
            public Champions Teemo;
            public Champions Thresh;
            public Champions Tristana;
            public Champions Trundle;
            public Champions Tryndamere;
            public Champions TwistedFate;
            public Champions Twitch;
            public Champions Udyr;
            public Champions Urgot;
            public Champions Varus;
            public Champions Vayne;
            public Champions Veigar;
            public Champions Velkoz;
            public Champions Vi;
            public Champions Viktor;
            public Champions Vladimir;
            public Champions Volibear;
            public Champions Warwick;
            public Champions Xerath;
            public Champions XinZhao;
            public Champions Yasuo;
            public Champions Yorick;
            public Champions Zac;
            public Champions Zed;
            public Champions Ziggs;
            public Champions Zilean;
            public Champions Zyra;
        }

        public class Champions
        {
            public string version;
            public string id;
            public string key;
            public string name;
            public string title;
            public string blurb;
            public Dictionary<string, int> info;
            public Dictionary<string, string> image;
            public List<string> tags;
            public string partype;
            public Dictionary<string, double> stats;
        }

When i initialize it values are automatically assigned to all the members. That all works fine

ChampionIds championIds = JsonConvert.DeserializeObject<ChampionIds>(json2); //Assignment works perfect!

And now i can access all the values as so. Just for an example of usage

Console.WriteLine(championIds.data.Aatrox.id);
Console.WriteLine(championIds.data.Aatrox.key);

Console.WriteLine(championIds.data.AurelionSol.version);
Console.WriteLine(championIds.data.AurelionSol.title);

But the problem is i want to get all the different champions keys and names into a Dictionary. So something like this.

Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();
ChampIdDict.Add(championIds.data.Aatrox.key, championIds.data.Aatrox.name);

And i want to do this for each champion. For an example like this

Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();
ChampIdDict.Add(championIds.data.Aatrox.key, championIds.data.Aatrox.name);
ChampIdDict.Add(championIds.data.Ahri.key, championIds.data.Ahri.name);
ChampIdDict.Add(championIds.data.Akali.key, championIds.data.Akali.name);
//and so on

But i dont want to make 100 lines in my code of this way. So i iterate through all members and get their names easily with this code

FieldInfo[] fields = typeof(Data).GetFields();
foreach (var field in fields)
{
     Console.WriteLine(field.Name);
}

And the result is this

Aatrox
Ahri
Akali
Alistar
Amumu
Anivia
//and so on

How do i make it so i can do this

FieldInfo[] fields = typeof(Data).GetFields();
foreach (var field in fields)
{
    Console.WriteLine("Inserting champion = " + field.Name + " into the dictionary");
    string key = championIds.data.(field.Name).key;
    string name = championIds.data.(field.Name).name;
    ChampIdDict.Add(key, name)
}

The result is that i simple get the champion id from a website and i say string returnedChampionId = //from website ex. 266 string championName = ChampIdDict["266"];

Thanks for reading. Hope you can recommend something





get number of methods and variable in a class Swift iOS like reflection in Java

How to get number of methods and variable in a class Swift iOS like reflection in Java.

like get Class's getDeclaredMethods() and getDeclaredFields().
getDeclaredMethods()       //will return array of methods defined.
getDeclaredFields()        //will return array of variables defined.





MakeGenericMethod with custom type

I made my own Type class for some reason, it works with most cases except MakeGenericMethod. Seems that MakeGenericMethod does not support custom types.

Is it possible to use generics with my type system?

Here's what I tried. https://dotnetfiddle.net/F92t8Z

And, here's .Net implementation https://github.com/dotnet/coreclr/blob/a64cb0a41a4ebeb4a61b8b0f1f2eeeff8dd539c9/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs#L625-L633





dimanche 21 juillet 2019

Java Reflection IllegalAccessException [duplicate]

This question already has an answer here:

I want to change the value of a static final field, and my code has no problem when the test method has nothing else. IllegalAccessException is only thrown when the field has been getField before changing it. I wonder if there is a way to resolve it or just don't getField before changing the static field?

Tests.java: nothing is thrown

public static final String b = "default";

System.out.println("######## setField() ########");
System.out.println(b);
Reflections.setField(Tests.class, "b", "changed");
System.out.println(b);

Tests.java: IllegalAccessException is thrown

public static final String b = "default";

System.out.println("######## setField() ########");
System.out.println(Reflections.getField(Tests.class, "b"));
System.out.println(b);
Reflections.setField(Tests.class, "b", "changed");
System.out.println(b);

Reflections.java

public static void setField(Class<?> clazz, String name, Object value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    setField(null, value, clazz, name);
}

private static void setField(Object instance, Object value, Class<?> clazz, String name) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    requireNonNull(clazz);
    requireNonNull(name);

    Field field = clazz.getDeclaredField(name);
    field.setAccessible(true);
    breakFinal(field);
    field.set(instance, value);
}

public static Object getField(Class<?> clazz, String name) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    return getField(null, clazz, name);
}

private static Object getField(Object instance, Class<?> clazz, String name) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    requireNonNull(clazz);
    requireNonNull(name);

    Field field = clazz.getDeclaredField(name);
    field.setAccessible(true);
    return field.get(instance);
}

public static void breakFinal(Field field) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    requireNonNull(field);

    Field modifiers = Field.class.getDeclaredField("modifiers");
    modifiers.setAccessible(true);
    if((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) {
        modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    }
}

It shouldn't throw any exception, what's wrong?

java.lang.IllegalAccessException: Can not set static final java.lang.String field cn.glycol.tutils.Tests.b to java.lang.String
    at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(Unknown Source)
    at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(Unknown Source)
    at sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl.set(Unknown Source)
    at java.lang.reflect.Field.set(Unknown Source)
    at cn.glycol.tutils.reflections.Reflections.setField(Reflections.java:245)
    at cn.glycol.tutils.reflections.Reflections.setField(Reflections.java:221)
    at cn.glycol.tutils.Tests.test(Tests.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)





Can Reflection work between two WARS running under the same process?

Assume I have multiple WAR files deployed under a wrapper, all the WARs run under the same process. Can I use reflection to access class information between different WARs?

I know that of course we can't use Reflection between two independent processes. But what about the scenario I described?





Get the list of classes that implements interface when code is used as a library in another project

I have class A implements MyInterface, class Manager, where I have load() method, and class with main, where I create instance of manager class, and call method load:

void load() throws Exception {
    final Reflections reflections = new Reflections("com.example");
    final Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);
    for (Class<? extends MyInterface> clazz : classes) {
        MyInterface interface = clazz.newInstance();
        /..../
    }
}

My interface and class has same package "com.example". I create JAR file with this 4 classes and atach to diferent project, where I call my main method. But someone can also implements my interface, and I have no idea, how my method load() can find this new class and create new instance (and there is no restriction for package name for new class)? Maybe someone know, how to do it? In this example I use org.reflection. Tkansk!





Its possible to get a param name in a method where the param is the result of a function

When you pass to a function other functions as params there is a way to get the param functions names ?

I tried with reflection but looks like the information do not appears.

public static String LeftFunction(String left) {
  ... Do stuff
  return left;
}

public static String RightFunction(String right) {
  ... Do stuff
  return right;
}

Now if I use a main function like

findRoute(LeftFunction("street 1"), LeftFunction("street 2"), RightFunction("Street 3"));

Is there a way where findRoute function can know if the param 1, 2, 3 .. is called from function left, right, up ....





Can we get the actual argument name of a method at runtime using reflection?

I have the below method in one of my classes. public String sampleMethod(final String sampleString){}

I have a method object "m" of the above method and doing a m.getParameters()[0].getName(); and it gives me String "arg0" Is there a way to get the actual argument name "sampleString" instead of "arg0" using "Reflection"?

Thanks in advance, Madhu