vendredi 31 mars 2017

Java protected fields shows as public

Have any class such as

public class Example {
    public String pub;
    protected String prot;
}

But in class which try to get public fields I see prot field as public. code of getting field:

public static List<Field> getPublicFields(Class targetClass) {
    List<Field> result = new ArrayList<>();
    result = Arrays.asList(targetClass.getFields());
    for (int i = 0; i < result.size(); i++) {
        Field currentField = result.get(i);
        int modifiers = currentField.getModifiers();
        if (Modifier.isStatic(modifiers) ||
                currentField.isSynthetic() ||
                !Modifier.isPublic(modifiers)) {
            result.remove(i);
            i--;
            continue;
        }
    }
    return result;
}

What am I write incorrect?





JAVA: Casting a String class to a String

import java.lang.reflect.Field;

public class ReflectGetFields {
    public void modeString() throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException{
        ReflectionPoint rp = new ReflectionPoint(1,2);
        Field[] fields = rp.getClass().getFields();
        System.out.println(fields);
        for (int i = 0; i < fields.length; i++) {
            if(fields[i].get(rp)==Class.forName("java.lang.String"));
            {
                String sss = (String) fields[i].get(rp);
                StringBuilder strb = new StringBuilder(sss);
                for (int a=0;i<strb.length();i++) {
                    if (strb.charAt(a)=='b') {
                        strb.setCharAt(a, 'a');
                    }
                }
            }

        }

        System.out.println(rp.toString());
    }


    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        ReflectGetFields rgf = new ReflectGetFields();
        rgf.modeString();
    }
}

Eclipse says :

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.github.user3301.Reflection.ReflectGetFields.modeString(ReflectGetFields.java:11)
    at com.github.user3301.Reflection.ReflectGetFields.main(ReflectGetFields.java:36)

I just don't know where did I do wrong as fields[i].get(rp) returns a field in the class and there is a if statement to check if it is a String type, so why it cannot be cast into a String type?





Access to not defined instance of IDisposable into "using" statement

I have this piece of code:

using(var a = myFunction()){

    a.Process();

}

There is some way to reference not defined instances into the using statement?

I mean, to write some like:

using(myFunction()){

    [Reflection?, another stuff?][0].Process();

}

Some clue?





Java Complex Object Replace

I never faced a requirement like that and I am pretty confused how can I implement that.

Lets consider the following Beans:

Company{
String companyName;
String companyId;
Person person;
//getter and setters
}

Person{
String id;
String name;
String lastName;
List<Address> address;
//getter and setters
}

Address{
String id;
String name;
String description;
//getter and setters
}

So the hierarchy would be like this:

Company has Person has Address

What I have to do is, replace all String fields with other String, for instance

Company.companyName = "Hi there #xyz"

Address.name = "St. Example #xyz"

I need to replace the char #xyx with #abcd, for instance.

The object is much more complex than that and has a huge hierarchy.

I tried to find some API that would help me to do that, however I couldn't find anyone (I don't know if look correctly).

A solution that I have is in each getter method replace the char, however I don't think that is the best way to solve that.

I appreciate your help.

Thanks in advance.





Filter a list of objects with objects inside dinamically

I have an object scores like this

public class Score{
    public Client _client { get; set; }
    public Offer _offer{ get; set; }
    public float _scoreValue { get; set; }
}

Afterwards this class is used in a List<Score> scores, now I want to dynamically filter the List using properties of the client or the offer. The data structure that feeds this filters knows this.

For example I want to filter the list of scores based on client.name ==JohnDoe LINQ is not an option because the property that I am going to use to filter in each case is different.

I already did some research and found out that Expressions Tree are the way to go, but I have some difficulty implementing it.





How to get generic argument name via reflection

given generic class

class Foo<TData> { }

and concrete type

var type = typeof(Foo<string>) //Fpp`[System.String]
var genericType = type.GetGenericTypeDefinition(); //Foo`1[TData]

I would like to get "TData". Or the other way: Get the value of the generic argument based on generic argument name:

GetGenericArgumentType(typeof(Foo<string>), "TData") //should return System.String





Cannot create a compilation in Roslyn from source code

For test purposes, I need to get a System.Reflection.Assembly from a string source which contains a source code. I am using Roslyn:

SyntaxTree tree = CSharpSyntaxTree.ParseText(source);
CSharpCompilation compilation = CSharpCompilation.Create("TestCompilation", new[] { tree });

Assembly assembly = null;
using (var stream = new MemoryStream())
{
    var emitResult = compilation.Emit(stream);
    if (!emitResult.Success)
    {
        var message = emitResult.Diagnostics
            .Select(d => d.ToString())
                .Aggregate((d1, d2) => $"{d1}{Environment.NewLine}{d2}");

        throw new InvalidOperationException($"Could not emit assembly.{Environment.NewLine}{message}");
    }

    stream.Seek(0, SeekOrigin.Begin);
    assembly = Assembly.Load(stream.ToArray());
}

As you can see my attempt here is to emit a CSHarpCompilation object so that I can get the Assembly later. I am trying to do this with:

var source = @"
  namespace Root.MyNamespace1 {
    public class MyClass {
    }
  }
";

Emit errors

But I fail at var emitResult = compilation.Emit(stream) and enter the conditional which shows the error. I get 1 warning and 3 errors:

  • Warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
  • (3,34): Error CS0518: Predefined type 'System.Object' is not defined or imported
  • (3,34): Error CS1729: 'object' does not contain a constructor that takes 0 arguments
  • Error CS5001: Program does not contain a static 'Main' method suitable for an entry point

So it seems I need to add reference to mscorelib and it also seems like I need to tell Roslyn that I want to emit a class library, not an executable assembly. How to do that?





jeudi 30 mars 2017

Issue activating a generic type with generic array in constructor parameters

I have a very strange issue with the following code:

using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuples1 = GimeStringTuples("foo", "bar");
            var testTuples2 = GimeTuples("foo", "bar");
            Console.ReadKey();
        }

        public static object GimeStringTuples(params string[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(string)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            return Activator.CreateInstance(specificType, values);
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);

            dynamic result;
            string[] testArgs = { "foo", "bar" };
            result = Activator.CreateInstance(specificType, testArgs);
            result = Activator.CreateInstance(specificType, values);
            return result;
        }
    }
}

It's failing on the second to last line:

result = Activator.CreateInstance(specificType, values);

This is weird since it's basically identical to the line that executes just before it:

result = Activator.CreateInstance(specificType, testArgs);

In both cases, the same argument is being passed as the specificType parameter and a string[2] is being passed as the second parameter.

And the GimeStringTuples method works just fine... although there are no generics involved there - which is maybe the hint.

Can anyone explain this unusual behaviour?





In C++, can I specify or select a member of a class ( and use it as parameter )?

For example, let's say I have:

Class AB { float a,b; };

How do I write one function that can process either "a" or "b", based on a parameter that's passed in, in a "proper" way ? I want to do something like this:

float getSqrt(AB x, ClassMemberSelector s) 
{ return sqrt(x.s); }

AB x;
getSqrt(x, SelectClassMember(AB::a) ); //get square root of x.a
getSqrt(x, SelectClassMember(AB::b) ); //get square root of x.b

Thanks.





Invoke Class Method using Reflection with different params in constructor?

Hello i am very new to c# reflection and i have the following problem.

I have a CommandDispatcher class that invokes a certain Command class that does something.

For now i use a switch to determinate what command to invoke.

i wanted to simplify the code by using reflection to invoke the right command and get rid of the switch for good.

But each command takes a certain service or more in its constructor. I don't want to change that part . I understand that if i had no services passed in the constructor the code would work fine.

So how can i invoke my commands with reflection when each command takes one or many services.

Here is an image for better understanding: The code with color indicators

I left the switch not commented out for easier reading.

Here is the code in pastebin: http://ift.tt/2ofr0A2

My search did not result in finding anything to solve my problem.





c# Assembly.LoadFrom with dynamic AssemblyResolve

I'm kind of stuck with dynamically loading plugins:

Theory: (Plugin) Dlls in a specific folder:

foreach(string path in Directory.GetFiles(...))
{
    Assembly myPlugin = Assembly.LoadFrom(path);
    foreach(Type type in myPlugin.GetTypes().Where(t => typeof(myPluginBaseClass).isAssignableFrom(t)))
    {
        Activator.CreateInstance(type);
    }
}

So far so good. Now there are issues with additional references in those assemblies, which can be solved by catch(ReflectionTypeLoadException) (to removed all null Types) and AppDomain.CurrentDomain.AssemblyResolve += ... (to manually look for those missing dlls)

Now here is the issue: The referenced missing assemblies are specific for each implemented Plugin, so I need a individual search behavior implemented in each Plugin. My ideas / solutions so far:

  • Having a global list of all possible DLL directories in my main application -> stupid because this won't allow to add further plugins without changing the main application code
  • Having a (non static) dictionary of specific dll paths in each plugin -> can be forced by the myPluginBaseClass using virtual/abstract; But can't be accessed before creation of the instance (where those AssemblyResolveEvents are fired), so not helpful
  • Having a (static) dictionary of specific dll paths in each plugin -> can be read before instantiation by using Reflection, but I can't add this to my myPluginBaseClass as a defined template, so errors possible
  • Creating a individual Domain for each plugin and let them handle their own AssemblyResolveEvent -> But how?

I hope you can help!

Thanks in advance! Robin





How to display enum dropdown values with space in it

I am new to VB.Net and I have a dropdown where I need to show some values but it should have space in it.

I think we cannot use spaces in enum as they are identifiers. Below is what I have till now

<td><asp:Label ID="Label1" runat="server" Text="Live:" /></td>
<td><asp:DropDownList ID="cbxUrlVersion" runat="server" Width="15%" onchange ="checkboxStatus();"/></td>

.aspx.vb file

clsGlobal.BindComboToEnum(cbxUrlVersion, GetType(SIM_BusinessObjects.Enumerations.WebSiteVersion))

Enum File:

Public Enum WebSiteVersion
    UseV9 = 1
    Usev10 = 2
End Enum

I looked into this solution Space in enum but it did not help me. Please guide me here.1

EDIT

Public Enum WebSiteVersion
    <Description("Use V9")>
    UseV9 = 1
    <Description("Use V10")>
    Usev10 = 2
End Enum





Swift equivalent of C#'s IsAssignableFrom

In C#, given two types, I can say something like

var stringType = typeof(string)
var intType = typeof(int)
var assignable = stringType.IsAssignableFrom(intType)

The value of assignable would be false since an int cannot be assigned to a string.

Is there any way to do this in Swift?

func isAssignable<T1, T2>(_ type1: T1.Type, from type2: T2.Type) -> Bool {
    // What's the implementation here?
}

let assignable = isAssignable(String.self, from: Int.self)

My suspicion is that this is not currently possible.





Extract JFrame from external jar file

i am working on a project in Eclipse where i need to extract a Jframe component from one external jar file.

The intention of this is to access via code to all java swing / awt components included. Something like control+shift+F1 debug mode of Eclipse.

I'm using Java Reflection to open the interface, read fields and read the methods; but i don't know how to do the next step to extract the swing objects.

File f = new File("C:/.../File.jar");
    ClassLoader cl = new URLClassLoader(new URL[] { f.toURI().toURL() }, null);
    final Class<?> claxx = cl.loadClass("JSwing");
    final Method main = claxx.getMethod("main", String[].class);

    Field[] fields = claxx.getDeclaredFields();
    for (Field field : fields) {
       System.out.println("field: " + field.getName());
    }

    Method[] methods = claxx.getDeclaredMethods();
    for (Method method : methods) {
        System.out.println("method: " + method.toString());
    }
EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                main.invoke(claxx, new Object[] {null} );
            } catch (Throwable th) {
                // TODO
            }
        }
    });

Obtained------------------------------------------

field: frmJavaswingui

field: txtJavaSwingUi

method: public static void JSwing.main(java.lang.String[])

method: private void JSwing.initialize()

The interface of the application

¿Any idea to extract the components of "frmJavaswingui"?





C# - how to get the name of internal variables used in a method

How is it possible (maybe through Reflection or Roslyn APIs) to get the list of internal variables that are used in a class method?

For example, in the following code:

class C1{
   private int var1;
   public string var2;

   void action1()
    {
       int var3;
       var3=var1*var1;
       var2="Completed";
   }
}

I would like to get var3,var1 and var2 as the list(as name and type) of variables used in the action1() method.

Secondly, I need to identify which of the above variables appear on the left side of an expression; i.e., their values have been modified in this method.

I think the answer lies in using Roslyn, but I have no idea how. Thanks!





Java Help For Custom Functions

Please help as how can I achieve below in java.

public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}

I may be wrong in many aspect here with my above code. I am sorry for that. The expected output here is

TRUE
Printing iteration #1

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3





Beanshell scripting with Java web based application

I am working on web based java application, where we want to allow user to write beanshell script to enhance the automation script of selenium. We record the steps performed by user but that is not sufficient as there might be other peace of code required which are purely java class code or like beanshell script. If I am not wrong then we can write class like code in beanshell and can run.

I need to know who I can achieve this? Is there any other way we can achieve this? Is there any limitation in beanshell to use it will java web based application?

We need to make sure that user is able to create object or class and also able to call methods and other stuff like normal java code allow.

I would appreciate your inputs and your guidance.





How does Class.forName(..) work, detailed?

First of all, I know that Class.forName() load a specific class to classloader and call it's static initializers. But, not long ago I found a problem in my company's application, we use some Http Client which call every http request Class.forName(...), that's cause problems during peaks of load. It locks hundreds of threads in monitor inside forName(...).

Here is the picture of my threads, they all waiting monitor!!!

enter image description here So, here is my questions:

  1. Is it scan classpath and all jars inside web application? (can it be a long operation?)
  2. Is it scan every call or if the class already loaded - it doesn't scan classpath?




mercredi 29 mars 2017

The difference between running a scala script directly vs through a scala shell

I ran into the "No TypeTag available for" error when running a simple script:

import scala.reflect.runtime.{universe => ru} 
case class Person(name: String)
val classPerson = ru.typeOf[Person].typeSymbol.asClass

The script is an example from Scala Reflection Doc. According to this post, the error is caused by the fact that the case class is not defined at the top level. I know scala automatically compiles a scala script into a class before running it, thus making the case class a internally defined class, but the same script would work if it is run in a scala shell. So what is the difference between running a scala script and running the same script through the scala shell?





Javassist throwing notfound / null pointer in CtMethod.make and getDeclaredMethod using OSGI

javassist is throwing null pointer in CtMethod.make com.company.test is the package of the Activator and Joe

public class Activator implements BundleActivator {

public Class<?> creerClasse() {
    CtClass toGenerateClass;
    ClassPool pool;
    pool = ClassPool.getDefault();
    try {
        Class c;
        c = Class.forName("com.company.test.Joe");
        pool.appendClassPath(new ClassClassPath(c));
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    pool.importPackage("com.company.test");

    toGenerateClass = pool.makeClass("Test118");

    try {
        toGenerateClass
                .addMethod(CtMethod
                        .make("public void afficher (com.company.test.Joe msg) { System.out.println(msg); } ;",
                                toGenerateClass));
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }

    try {
        return toGenerateClass.toClass();
    } catch (CannotCompileException e) {
        e.printStackTrace();
        return null;
    }
}


public void start(BundleContext context) throws Exception {


        Class<?> genClass = creerClasse();
        Class<?> c = Class.forName("com.company.test.Joe");

        for (Method me : genClass.getDeclaredMethods()) { // test print, ok
            System.out.println(me);
        }

        Method method = genClass.getDeclaredMethod("afficher", c);

        Joe person = new Joe();
        person.setId(17);
        method.invoke(genClass.newInstance(), person);

}

}

and when i instansiate pool with pool = new ClassPool(true); it throws java.lang.NoClassDefFoundError: com/company/test/Joe in getDeclaredMethod





mardi 28 mars 2017

Pushing Python introspection to limits

Simple question – can I print the source code of this if?

if args and args[0][0] == '-':
  if args[0] in ('--help','-h','-?'):
    print_source_of_block(level=2)
  icase = 'i' in args[0]
  desc = 'd' in args[0]
  args = args[1:]

Please don't ask me why I need it, nor give me advice on how to write user help. I want to know it because I'm curious.





Assert specific constructor called by child class

I am trying to write a test to verify that child classes call a specific base class' constructor. Effectively, IDs for my entities are generated when the object is instantiated by the server. I am using NHibernate as my ORM, and so I need a 0-parameter constructor. I would prefer that this constructor not generate a Guid everytime that NHibernate hydrates an entity, so I created a second constructor for my base entity with a Guid as a paramter.

It looks something like this

public abstract class EntityBase {
    public Guid ID {get; protected set;}

    protected EntityBase() { }

    public EntityBase(Guid id) { ID = id }

    public static Guid NewID => GenerateGuid();
}

public class Entity : EntityBase {
    public int X {get; set;}

    protected Entity() { }

    public Entity(int x) : base(NewID) { X = x; }
}

This test I want to write should assert that all constructors (except the 0-parameter constructor) of all concrete child classes of EntityBase call the correct base constructor:

public EntityBase(Guid id) { ID = id }

Currently, my code loops through constructors on all concrete classes assignable from EntityBase, but I don't know how to make the final check. Research into solutions suggested attempting to read IL using reflection. I considered trying to check if 'NewID' had been called, but was unable to find any accomplish that either.

Is there a way to achieve this, or is my solution to the NHibernate problem the real issue?





Check if a reflect.Type does implements another reflect.Type

Heys guys, I'm creating a library in golang for my company. I want the client pass to us a callback with func(t ) error; Since there's no generics in Go, I'm trying to check the arguments and return type through reflection.

But I'm failling right now. Any help?

func check(F interface{}) bool {
    errorInterface  := reflect.TypeOf((*error)(nil)).Elem()
    if tpFunc := reflect.TypeOf(Func); tpFunc.Kind() != reflect.Func {
        return false
    } else if tpFunc.NumIn() != 1 || tpFunc.NumOut() != 1 {
        return false
    } else if tpArg := tpFunc.In(0); tpArg.Kind() != reflect.Ptr || tpArg.Elem().Kind() != reflect.Struct {
        return false
    } else if tpRet := tpFunc.Out(0); tpRet.Implements(errorInterface)  {
        return false
    }
    return true
}



type T0 struct {
   A int64
   B float
}

func F0(t *T0) error {
  ...
}

func F1(t *T0) int {
  ...
}





Array with datatype of a reflected class

I want to adress this constructor:

public PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction paramEnumPlayerInfoAction, EntityPlayer[] paramArrayOfEntityPlayer) {
    [...]
}

using the code below.

ReflectionHandler.getNMSClass(String) is a Method utilizing the Class.forName()-Method to get the class in a shared package, hardcoded into the .getNMSClass().

01 Constructor<?> npcConstructor = ReflectionHandler.getNMSClass("EntityPlayer").getConstructor(server, world.getClass(), GameProfile.class, ReflectionHandler.getNMSClass("PlayerInteractManager"));
02 Constructor<?> playerInteractManagerConstructor = ReflectionHandler.getNMSClass("PlayerInteractManager").getConstructor(world.getClass().getSuperclass());
03                  
04 playerInteractManager = playerInteractManagerConstructor.newInstance(world);
05 npc = new Object[]{npcConstructor.newInstance(craftServer.getMethod("getServer").invoke(Bukkit.getServer()), world, new GameProfile(UUID.randomUUID(), args[1]), playerInteractManager)};
06                  
07 Constructor<?> packetPlayerInfoConstructor = ReflectionHandler.getNMSClass("PacketPlayOutPlayerInfo").getConstructor(ReflectionHandler.getNMSClass("PacketPlayOutPlayerInfo$EnumPlayerInfoAction"), 
08    Class.forName("[Lnet.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + ".EntityPlayer;"));
09 Constructor<?> packetEntitySpawnConstructor = ReflectionHandler.getNMSClass("PacketPlayOutNamedEntitySpawn").getConstructor(npc[0].getClass().getSuperclass());
10
11 packetPlayerInfo = packetPlayerInfoConstructor.newInstance(ReflectionHandler.getNMSClass("PacketPlayOutPlayerInfo$EnumPlayerInfoAction").getField("ADD_PLAYER"), npc);
12 packetEntitySpawn = packetEntitySpawnConstructor.newInstance(npc[0]);

I want to instantiate the constructor in line 11 but get a java.lang.IllegalArgumentException: argument type mismatch, for that line, (propably) because npc is an array declared like this Object[] npc; as an object, even if the constructor requires an EntityPlayer[].

My question is how you solve that problem or rather how you declare npc as an EntityPlayer[], without importing EntityPlayer. I'd use reflection if I knew the greater details, wich I unfortunately don't.

Thanks in advance and have a wonderful day

rapt0r





Dynamically instantiate classes which implement an interface and invoke interface method

I have an interface, LogParser, consisting of a single method parse(String x). I also have an ArrayList containing the names of multiple classes which all implement LogParser. Is it possible to loop through this list of class names and dynamically instantiate their respective classes and invoke parse(String x)?

The issue I've had is that the classes do not have zero-argument constructors, so I have run into InstantiationException a lot attempting to invoke the parse method through reflection.

Thanks!





Can I get the instance of the calling object in Java?

There's a library which calls my method with a few arguments. I'd like to receive another argument, but the library doesn't provide it to the method it calls.

By decompiling the library, I can see that it has the argument, and it's assigned to an instance variable (not private, but not public either.) I know I can get at the variable using reflection if I have the instance, but I don't have the instance, either.

Is there a way I can get at the instance? SecurityManager has getClassContext(), but that just gives me the class of the instance - I want the instance itself.

As a quick example of what I want:

public class A {
    int b;
    public A(int b, int c) {
        this.b = b;
        D(c);
    }
}

public class D {
    public D(int c) {
        // Somehow I want to get at the calling instance of A's b from here,
        // and A belongs to a library which I didn't write.
    }
}

Alternatively... I do know that b was used as an argument on the callstack. So if someone knows how I could access the b which was passed into A's constructor, that would be acceptable.

If neither of these are doable... I can decompile A and compile it the way I want, and then I'd either need to do some classloading wizardry or I'd have to modify the contents of the jar. Neither of those sound desirable, so I'm hopeful someone knows how to either access the instance of A or the argument b from the call stack.





reflect.New returns

I am using reflection for a library I'm building but there's something I don't understand about reflect.New.

type A struct {
    A int
    B string
}

func main() {

    real := new(A)
    reflected := reflect.New(reflect.TypeOf(real)).Elem().Interface()
    fmt.Println(real)
    fmt.Println(reflected)
}

Gives:

$ go run *go
&{0 }
<nil>

Isn't reflect.New supposed to return &{0 } too? (Runnable Version)

Ultimately, I wish to be able to iterate over the fields of the reflected struct (reflected.NumField() gives reflected.NumField undefined (type interface {} is interface with no methods)) and use SetInt, SetString and so on.

Thanks,





why SomeClass::class is KClass

I want to print values of properties of my class.

fun print() {
    val cl = this::class
    cl.declaredMemberProperties.filter {it.visibility != KVisibility.PRIVATE}.forEach {
        println("${it.name} = ${it.get(this)}")
    }
}

When I try to build this code I get compiler error:

Error:(34, 40) Kotlin: Out-projected type 'KProperty1<out SomeClass, Any?>' prohibits the use of 'public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1'

When I change this to class name SomeClass everything is fine

fun print() {
    val cl = SomeClass::class
    cl.declaredMemberProperties.filter {it.visibility != KVisibility.PRIVATE}.forEach {
        println("${it.name} = ${it.get(this)}")
    }
}

So the problem is that compiler changers type of this::class to KClass<out SomeClass> instead of using KClass<SomeClass>. Any idea why does it happen?





Intellij shows syntax error while using Scala reflection

I am writing scala in Intellij, the following codes can run correctly, but the IDE gives a syntax error report, Intellij recognises c.value as generic type A in both cases :

object TypeTagTest extends App {
  case class Container[+A](value: A)

  matchContainer(Container("1"))
  matchContainer(Container(1.0))

  matchContainer1(Container("20"))
  matchContainer(Container(16.0))

  def matchContainer[A: TypeTag](c: Container[A]) = c match {
    case c: Container[String @unchecked] if typeOf[A] <:< typeOf[String] => println("type of string: " + c.value.toUpperCase)
    case c: Container[Double @unchecked] if typeOf[A] <:< typeOf[Double] => println("type of double: " + math.sqrt(c.value))
    case c: Container[_] => println("other")
  }

  def matchContainer1[A: ClassTag](c: Container[A]) = c match {
    case c: Container[String @unchecked] if classTag[A] == classTag[String] => println("type of string: " + c.value.toUpperCase)
    case c: Container[Double @unchecked] if classTag[A] == classTag[Double] => println("type of double: " + math.sqrt(c.value))
    case c: Container[_] => println("other")
  }
}

The results: type of string: 1 type of double: 1.0 type of string: 20 type of double: 4.0

Thanks for the help.





Getting all types under a userdefined assembly

I am trying to get all the types defined under a particular userdefined namespace

Assembly.GetEntryAssembly().GetTypes().Where(t => t.Namespace == "namespace")


    <>c__DisplayClass3_0    
    <>c__DisplayClass4_0    
    <>c__DisplayClass6_0    
    <>c__DisplayClass2_0    
    <>c__DisplayClass2_1    
    <>c__DisplayClass2_2    
    <>c__DisplayClass2_3    
    <>c__DisplayClass2_4    
    <>c__DisplayClass2_5    
    <>c__DisplayClass2_6    
    <>c__DisplayClass2_7    
    <>c__DisplayClass2_8

My question Why am i getting these extra type which are not defined under that namespace?

how do i select type that are user defined types?

some one explain me what are these and how they get defined under a userdefined namespace.





How to check if referenced dll is needed for class on runtime

I hav ea program which dynamically loads and adds elements based on all found dlls in a given directory. (in short: Assembly.LoadFrom("...xyz.dll").GetTypes().Where(t => typeof(MyBaseClass).isAssignableFrom(t).Select(t => Activator.CreateInstance(t)))

Now some of my Dlls (including multiple classes derived from MyBaseClass) require additional referenced Dlls, which are not always included (like when using an API-Dll from another program). Those are typically handled by my AppDomain.CurrentDomain.AssemblyResolve event, where I dynamically load those missing API-DLLs based on some installation paths) As a result, when using assembly.getTypes(), I get an "ReflectionTypeLoadException ex" with a subtype "FileNotFoundException" as part of the ex.LoaderExceptions.
To clarify: this exception is ok, because some API-Dlls are part of other programs; so if you run my program on another PC without these programs installed, of course the referenced API-DLLs are missing (And adding them to my program is not allowed).

My question now is: how can i filter my listed types (either from assembly.GetTypes() or ReflectionTypeLoadException ex.Types) to remove those classes which actually use one of those missing API.DLLs (or use another class which use one of those etc.)? - assembly.GetReferencedAsseblies() only lists all referenced assemblies of my top level assembly. But as mentioned, this can contain multiply classes based on MyBaseClass, of which e.g. only one actually uses the missing API-DLL (defined by "using ..." at the start)

As an addition: can I automatically split my .CurrentDomain.AssemblyResolve event to their regarded top assemblies? Like having a (static?) resolve Method in each of my DLLs which handles missing sub-Assemblies instead of one method for all in my MainForm?

Thank you in advance!

Best regards, Robin





lundi 27 mars 2017

How can I reflect over and get the value from this inner class?

A user is passing me a string with a class name and another string with a field from that class that I'm supposed to use to extract some information with. Here are a couple of sample classes; they all inherit from the same base class:

public class PersonRow : Row
{
   public static readonly RowFields Fields = new RowFields.Init();

   public class RowFields : RowFieldBase
   {
      public Int32Field Id;
      public StringField FirstName;
      public StringField LastName;
   }

}


public class AutomobileRow : Row
{
  public static readonly RowFields Fields = new RowFields.Init();

  public class RowFields : RowFieldBase
  {
     public Int32Field Id;
     public StringField PaintColor;
     public StringField EngineSize;
  }
}

The user will give me something like 'PersonRow' and 'FirstName', from which I need to dive into the FirstName field and extract the value of a member in it called Expression.

I'll spare the details of what Int32Field and StringField are doing internally, but suffice it to say both these types have an Expression member which is a string I need to use.

I'm trying to use reflection to do this, and have gotten this far:

var myClassType = Type.GetType("PersonRow");
var myFields = myClassType.GetField("Fields", BindingFlags.Public | BindingFlags.Static);
var fieldListing = myFields.GetValue(null);

...at this point I have an object which is an array of PersonRow.RowFields. However I'm kind of stuck in going past this, in that I'm not sure how to enumerate over that array and extract the Expression value from the field I'm interested in?





How to get the type of the object that is being injected in Unity?

I have a type that receives another type in its constructor, which usually is the type of the object that creates it, e.g.:

public class Logger {
    public Logger(Type parent) { ... }
}

I would like to instruct Unity to resolve Logger passing as the argument to its constructor the type of the object that requires it. Something like:

// ... would be some directive to tell Unity to use the type that
/// depends on Logger
container.RegisterType<Logger>(new InjectionConstructor(...));

So that when I try to resolve MyService:

public MyService {
    public MyService(Logger logger) { ... }
}

it will return:

var logger = new Logger(typeof(MyService));
return new MyService(logger);

Is it possible? Is there another way of doing it?





Looking for the class of an Iterable to create a constructor using reflection

Good day,

I've got a question regarding reflection in Java. I want to instanciate a constructor for a class PacketPlayOutPlayerInfo using the following constructor:

public PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction paramEnumPlayerInfoAction, Iterable<EntityPlayer> paramIterable){
    [...]
}

To build the constructor i use this method

Constructor<?> packetPlayerInfoConstructor = ReflectionHandler.getNMSClass("PacketPlayOutPlayerInfo").getConstructor(
                                ReflectionHandler.getNMSClass("PacketPlayOutPlayerInfo$EnumPlayerInfoAction"), _____);

The first argument is working perfectly fine, but I somehow have to get the class of the interface Iterable to get the constructor to work... (or do I?)

Thanks in advance and have a nice day,

rapt0r





How can I create a data structure containing properties whose types are defined at runtime

I am working on a data visualisation tool. It retrieves a bunch of data from a plain text file and then draws various charts and graphs of that data.

So far I have been working with one set of data of which I know the types.

For example if I'm working with a CSV file that looks like this:

id, username, number of messages, message
23123124, @SomeUsername, 5, This 1s a 5tr1ng
89134349, @AnotherUsername, 8, Another string

Then I can store this in an object like this:

public class SomeClass
{
    private string id;
    private string username;
    private int numberOfMessages;
    private string message;
}

Then I just have a List<SomeClass>.

That's great and everything, but it will only work with that particular CSV file. I want to have a data structure that can be flexible, depending on the contents of the CSV file.

The number of properties and the names of those properties is easily discovered by reading the header row in the first line of the text file. What type each piece of data is isn't clear (e.g. an id could be stored as an int or a string), so I'm going to ask the user to tell the application what type to use for each property. I could do this by displaying the name of each property next to a dropdown with options of string, int, bool etc.

But how do I take that user input and create a data structure that contains properties of those types. So if the user goes through a form with 3 drop downs and selects "String", "Integer" and "Boolean", I effectively want an object that looks like this:

public class SomeClass
{
    private string someString;
    private int someInt;
    private bool someBool;
}

What is the best way of achieving this? I have a reasonable understanding of Generics but not sure how to use them in this case. I have heard of Reflection, the Type class and the dynamic keyword but don't really understand them. I have tried using Dictionaries but keep getting stuck. Are any of these options viable? Are they overkill? Am I overthinking this? HELP ME PLEASE! :D

Thank you!





dimanche 26 mars 2017

Trouble with Java Reflection

So I'm new to using reflection and I'm getting inconsistent results.

First I tried converting this line to reflection

userForm.setEquipment(currentForm.getFirstEquipment);

This is what I did and it seems to work.

try{
    Method setObject = userForm.getClass().getMethod("setObject", Shipment.class);
    setObject.invoke(userForm, currentForm.getFirstObject());
}
catch ( Exception e){
    Logger.error(e);
}

But when I tried something similar with a different line it doesn't work.

Here's what I started with.

List<Shipment> list = new ArrayList<Shipment>();
list.add(userForm.getFirstObject);

and this is what I have now, but it doesn't seem to work.

List<Shipment> list = new ArrayList<Shipment>();
try{
    Method add = list.getClass().getMethod("add", Shipment.class);
    add.invoke(list, userForm.getFirstObject());
}
catch ( Exception e){
    Logger.error(e);
}





TypeScript datatype reflection: is there a 'DataType' class?

I'm not sure whether classes are objects in TypeScript.

But would it be possible to code something like this? I couldn't find anything about it, so i'm assuming it's not possible, but still asking to make sure.

public datatype : DataType = String;





Executing code in every subclass on class loading

I'm trying to execute the same code in every subclass of a class once the class is loaded. I need to scan the classes fields using reflection to generate an outline of the data container/class.

Is there any way to do this without invoking a method of the superclass in every subclass once it is initialized? (e.g. inheriting the static initializer of the super class)





How implementation of Re-entrant lock and Synchronization is different

As per java source code

ReentrantLock's lock(non-fair) is as below.

public boolean lock(){
      int c=getState();
      if(c==0){
         compareAndSetState(0,1);
      }
}
//getState method
public int getState(){
    return state;
}
public boolean compareAndSetState(int expected,int update){
    unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

and value of stateOffSet is offset of state in memory(using reflection).

what i can understand from above code is ,when we call lock.lock(),first value of state fields in checked in memory,if it is zero then only lock is given to calling thread.

so my question is what happens when we user Synchronized key word? does in Synchronized also some field of lock is checked and set?

one more doubt,somewhere I read reentrant lock allows multiple wait queue,what does that mean?don't we have just one queue for both?





Deserialize XML without using Assembly.reflection

So I need help with trying to deserialize a large XML file to a class. My plugin runs in a extremely locked down appdomain where I cant reference the assembly its self. How can I Deserialize my xml string. I would not like to write it all by hand.

Below is the error that is thrown

[   3380094] Error invoking callback for event onClientResourceStart: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MethodAccessException: Error verifying System.Xml.Serialization.XmlSerializer:.ctor (System.Type,string): Method System.Reflection.Assembly:op_Equality (System.Reflection.Assembly,System.Reflection.Assembly) is not accessible at 0x00b7
[   3380094]   at System.Xml.Serialization.XmlSerializer..ctor (System.Type type) [0x00000] in <63deab55b0184b3986aa59caa8977082>:0 
[   3380094]   at ELS.configuration.VCF.load (ELS.configuration.SettingsType+Type type, System.String Data) [0x00026] in <de6203b91a5a474f9386b9994903dbe1>:0 
[   3380094]   at ELS.FileLoader.RunLoadeer (System.String name) [0x0012f] in <de6203b91a5a474f9386b9994903dbe1>:0 
[   3380094]   at ELS.ELS.<.ctor>b__5_0 (System.String obj) [0x00001] in <de6203b91a5a474f9386b9994903dbe1>:0 
[   3380094]   at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
[   3380094]   at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <a4e3abdd630b4c98a9d6f31a99197de6>:0 

The code below is the code that is throwing the error

data = new vcfroot();
Debug.WriteLine(typeof(vcfroot).ToString());
var serializer = new XmlSerializer(typeof(vcfroot));
var xmlreader = new XmlTextReader(Data);
if (serializer.CanDeserialize(xmlreader))
{
    object ddata = serializer.Deserialize(xmlreader);
}





Reflection Renders HashCode Unstable

In the following code, accessing the custom attributes of a SomeClass results in the hash function of SomeAttribute becoming unstable. What's going on?

static void Main(string[] args)
{
    typeof(SomeClass).GetCustomAttributes(false);//without this line, GetHashCode behaves as expected

    SomeAttribute tt = new SomeAttribute();
    Console.WriteLine(tt.GetHashCode());//Prints 1234567
    Console.WriteLine(tt.GetHashCode());//Prints 0
    Console.WriteLine(tt.GetHashCode());//Prints 0
}


[SomeAttribute(field2 = 1)]
class SomeClass
{
}

class SomeAttribute : System.Attribute
{
    uint field1=1234567;
    public uint field2;            
}





samedi 25 mars 2017

How to differentiate the types: Int32[] & Int32[*]?

Given the following code:

var type1 = typeof(int[]); // Int32[]
var type2 = Array.CreateInstance(elementType: typeof(int),
                                 lengths: new [] {0},
                                 lowerBounds: new []{1}).GetType(); // Int32[*]

Given an array type (a type where .IsArray returns true), how can I reliably differenciate between those two kinds of array types?

Without using any hacky solutions preferably (like instantiating the type or looking for "*" in the name).





invoking bean's setter via reflection in android application

so basically i have a hash map where the key is day of the week from monday to sunday and my Time class also contains those fields, now i want to set key values in that class using reflection. This is my code:

WorkingTime wt = new WorkingTime();
         for (String key : timeToSend.keySet()){
            String methodExtentionL = key;
            String methodExtentionU = methodExtentionL.substring(0,1).toUpperCase()+methodExtentionL.substring(1);
            Log.i(TAG, "updateWorkingTime: key value "+methodExtentionU);

            try {
                String methodName = "set"+methodExtentionU;
                Method setMethod = wt.getClass().getDeclaredMethod(methodName,String.class);
                setMethod.invoke(wt,timeToSend.get(key));


            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

This could not be simpler, but it is still throwing method not found exception:

java.lang.NoSuchMethodException: setFriday [class java.lang.String]
W/System.err:     at java.lang.Class.getMethod(Class.java:624)
W/System.err:     at java.lang.Class.getDeclaredMethod(Class.java:586)

for every day. Looked all over stackoverflow and all articles for this kind off issue says that the code is supposed to look like that, but still nothing... Any help would be much appreciated. Thanks!





Couldn't take value from JOptionPane.showInputDialog in other private method

I have created a JRadioButton called ConcatS, so if it is selected the input dialog box pop up and that input string I wanted to use in JButton called "Ok" i.e OperationOkActionPerformed method.

I'm using Java reflection to get private method's variable string, but couldn't get it working.

I'm using Java Swing.

private void OperationOKActionPerformed(java.awt.event.ActionEvent evt) {
    if (LenS.isSelected()) {
        String s = InputString.getText();
        int l = s.length();
        OutPut.setText(Integer.toString(l));
    }
    if (ConcatS.isSelected()) {
        Method s2 = Operations.class.getDeclaredMethod("ConcatSActionperformed", null);
    }
}

private void ConcatSActionPerformed(java.awt.event.ActionEvent evt) {
    String s1 = JOptionPane.showInputDialog("Input Second String");
}    





When is using reflection a good practice?

I recently learned about reflection in my course and was given an assignment to create objects from an XML file using reflection in Java. Through searching this site I'm noticing there seems to be a general consensus that using reflection, particularly in this way, is a bad idea. Odd to me because we were told this is one of the most useful things we'll learn this semester.

I have no control over my assignment so I'll just have to complete it this way anyhow. But I was wondering, when is using reflection a good practice? And what are some industry examples you might have where reflection was the best way to go about a problem?





What is the best way to instantiate a class using Reflection with the polymorphism?

I'm trying to use Reflection in java to
instantiate a Player with a Command Pattern likes below :

There is only one 'execute' method in a Command class,
And the InitiatePlayerCommand as its name , it will instantiate a
subclass of Player according to the playerClass passed in the constructor.

I have two kind of subclass of Player class : HumanPlayer and AiPlayer for polymorphism.

I expect it will instantiate one of them subclass and add into the playerList

but I have no idea what is the best way to reach this with Reflection. It always occurs a typecast error .

public class InitiatePlayerCommand implements Command{
private List<Player> playerList;
private String name;
private WarMode warMode;
private Class<?> playerClass;
public <T extends Player> InitiatePlayerCommand(String name, WarMode mode ,List<Player> list
        ,Class<T> playerClass){
    this.name = name;
    this.warMode = mode;
    this.playerList = list;
    this.playerClass = playerClass;
}

@Override
public void execute() throws InstantiationException, IllegalAccessException, IllegalArgumentException, NoSuchFieldException, SecurityException {
    Player player = (Player) playerClass.newInstance();
    player.setName(name);
    player.setWarMode(warMode);
    playerList.add(player);
}

public static void main(String[] argv){
    List<Player> playerList = new ArrayList<Player>();
    new InitiatePlayerCommand("Johnny",WarMode.MILITARY,playerList,HumanPlayer.class)
            .execute();  // this line get an error HumanPlayer.class isn't compatible to Class<T extends Player> playerClass
    System.out.println(playerList);

}

}

Is there any way to reach this without using Class<?>





vendredi 24 mars 2017

How to save and run dynamic generic methods

I am trying to run a generic method with a type I will only know at runtime. I can make this call using reflection but the performance is terrible. My research shows that you can create a delegate using reflection and then all subsequent runs will be much faster.

I would like to save these reflected delegates into a dictionary. My program would then check to see if the method was already defined and if not then it could create a new delegate.

My program has two main methods. The first one takes in a type of a class that will hold the results from a DataSet. The DataSet has multiple DataTables which need to be bound to properties. These properties are each a list of an object with the correct properties to hold the DataTable columns.

I realize that even if I make this work it might be too cleaver for long term support but it is now a puzzle that I must find an answer to :)

public static class Common
{
    //http://ift.tt/2nZeqlo

    private static Dictionary<Type, Delegate> _toListCache = new Dictionary<Type, Delegate>();

    #region Data bind methods

    /// <summary>
    /// Extension Method to bind DataSet to model properties
    /// </summary>
    /// <typeparam name="T">Type of model</typeparam>
    public static T ToModel<T>(DataSet ds)
    {
        //for this to function we need multiple tables with the first table being the DataSet ID
        ////EXAMPLE return value:
        ////Index DataTableName
        ////0     DataSetInfo
        ////1     ContractInfo
        ////2     InvoiceInfo
        if (ds.Tables.Count < 2) throw new DataException("Invalide DataSet format");

        var ob = Activator.CreateInstance<T>();
        PropertyInfo[] properties = typeof(T).GetProperties();

        DataTable setIds = ds.Tables[0];
        foreach (DataRow table in setIds.Rows)
        {
            //skip the first ID table
            if (table["DataTableName"].ToString() == "DataSetInfo") continue;

            int tableIndex = (int)table["Index"];
            string tableName = table["DataTableName"].ToString();

            //check if property exists matching the table name
            PropertyInfo property = ob.GetType().GetProperty(tableName);
            if (property != null)
            {
                //get list type
                Type propertyType = property.GetType();
                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))
                {
                    //Get type T out of List<T>
                    Type listType = propertyType.GetGenericArguments()[0];
                    DataTable dt = ds.Tables[tableIndex];

                    //call ToList with a dynamic type
                    if (_toListCache.ContainsKey(listType))
                    {
                        //delegate has already been defined
                        var list = _toListCache[listType].DynamicInvoke(dt);
                        property.SetValue(ob, list);
                    }
                    else
                    {
                        MethodInfo createDelegate = typeof(Common).GetMethod("AddDelegateToCache").MakeGenericMethod(listType);
                        var func = createDelegate.Invoke(null, new object[] { "ToList" });

                        var list = _toListCache[listType](dt);
                        property.SetValue(ob, list);
                    }
                }
                else
                    throw new TypeLoadException(string.Format("Property {0} is not a type of List<T>", tableName));
            }
            else
                throw new TypeLoadException(string.Format("Property {0} does not exist.", tableName));
        }

        return ob;
    }

    /// <summary>
    /// Extension Method to bind DataTable to model properties
    /// </summary>
    /// <typeparam name="T">Type of model</typeparam>
    public static List<T> ToList<T>(DataTable dt)
    {
        List<string> columns = (from DataColumn dc in dt.Columns select dc.ColumnName).ToList();

        FieldInfo[] fields = typeof(T).GetFields();
        PropertyInfo[] properties = typeof(T).GetProperties();
        List<T> lst = new List<T>();

        foreach (DataRow dr in dt.Rows)
        {
            var ob = Activator.CreateInstance<T>();

            ////for performance we will only look at properties
            ////sets field values that match a column in the DataTable
            //foreach (var fieldInfo in fields.Where(fieldInfo => columns.Contains(fieldInfo.Name)))
            //    fieldInfo.SetValue(ob, !dr.IsNull(fieldInfo.Name) ? dr[fieldInfo.Name] : fieldInfo.FieldType.IsValueType ? Activator.CreateInstance(fieldInfo.FieldType) : null);

            //sets property values that match a column in the DataTable
            foreach (var propertyInfo in properties.Where(propertyInfo => columns.Contains(propertyInfo.Name)))
                propertyInfo.SetValue(ob, !dr.IsNull(propertyInfo.Name) ? dr[propertyInfo.Name] : propertyInfo.PropertyType.IsValueType ? Activator.CreateInstance(propertyInfo.PropertyType) : null);
            lst.Add(ob);
        }

        return lst;
    }

    #endregion

    #region Generic delegate methods

    public static Func<T, object, object> AddDelegateToCache<T>(string method) where T : class
    {
        MethodInfo genericMethod = typeof(Common).GetMethod("GenericMethod", new Type[] { typeof(T) });
        Func<T, object, object> genericMethodFunc = GenericMethod<T>(genericMethod);
        _toListCache.Add(typeof(T), genericMethodFunc);
        return genericMethodFunc;
    }

    /// <summary>
    /// Runs a generic method with a dynamic type
    /// </summary>
    /// <typeparam name="T">Return type</typeparam>
    /// <param name="method">Target generic method</param>
    static Func<T, object, object> GenericMethod<T>(MethodInfo method) where T : class
    {
        // First fetch the generic form
        MethodInfo genericHelper = typeof(Common).GetMethod("GenericMethodHelper", BindingFlags.Static | BindingFlags.NonPublic);

        // Now supply the type arguments
        MethodInfo constructedHelper = genericHelper.MakeGenericMethod
            (typeof(T), method.GetParameters()[0].ParameterType, method.ReturnType);

        // Now call it. The null argument is because it’s a static method.
        object ret = constructedHelper.Invoke(null, new object[] { method });

        // Cast the result to the right kind of delegate and return it
        return (Func<T, object, object>)ret;
    }

    /// <summary>
    /// used to cast object to TParam and TReturn
    /// This allows fast dynamic generic methods to run
    /// </summary>
    static Func<TTarget, object, object> GenericMethodHelper<TTarget, TParam, TReturn>(MethodInfo method)
        where TTarget : class
    {
        // Convert the slow MethodInfo into a fast, strongly typed, open delegate
        Func<TTarget, TParam, TReturn> func = (Func<TTarget, TParam, TReturn>)Delegate.CreateDelegate
            (typeof(Func<TTarget, TParam, TReturn>), method);

        // Now create a more weakly typed delegate which will call the strongly typed one
        Func<TTarget, object, object> ret = (TTarget target, object param) => func(target, (TParam)param);
        return ret;
    }

    #endregion
}





Pass generic type class method as parameter

Is there any way to pass a method of a generic type as a parameter? What I try to achieve is something like this:

ListUtils.mapObjectToField( entries, Contact.getZipCode );

I pass a List<T> and a method from the generic class T. So far I am fine with the generic List but I am not able to achieve the method call.

public static <T, U> List<U> mapObjectToField( List<T>elements, /*generic method*/ )
{
    List<U> result = new ArrayList<>();

    for ( T current : elements )
    {
        result.add(current./*generic method*/);
    }
    return result;
}

No Java 8 as I am coding for Android min SDK 14.





Get local name of variable issued to function

want to get name of variable issued from outside.

For example:

def process(var):
  print name(var)#prints 'nice_name'

nice_name=1
process(nice_name)

Is it even possible in python?





Java reflection: Get inner instantiated field

I have an interface which looks like this:

public interface A {
    public interface B {
        public static final Cat cat = new Cat("Alice");
    }
}

Is there any way I can access the Cat object through reflection?

I have tried this:

Field catField = Class.forName("A.B").getField("cat");

But it gives me a ClassNotFoundException.

Thanks in advance!





Why I can't detect annotations from a loaded java class?

I have a plugin within i want to access to the class list of my model package from my maven project. Until now i just did this to load the classes into the plugin :

try {
            runtimeClasspathElements = project.getRuntimeClasspathElements();

        } catch (DependencyResolutionRequiredException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
        for (int i = 0; i < runtimeClasspathElements.size(); i++) {
          String element = (String) runtimeClasspathElements.get(i);
          try {
            runtimeUrls[i] = new File(element).toURI().toURL();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

newLoader = new URLClassLoader(runtimeUrls,
      Thread.currentThread().getContextClassLoader());
      try {          class=newLoader.loadClass("com.pkl.bc.personnaldata.model.Personne");

    if(class!=null)
        System.out.println(class.getCanonicalName());
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

here i can see the full name of my class.

System.out.println(class.getDeclaredFields());
System.out.println(class.isAnnotationPresent(EditColumn.class));
for (Field f : class.getDeclaredFields()) {

                EditColumn v = f.getAnnotation(EditColumn.class);
                if (v != null) {

                    System.out.println(v.tableName());
                    System.out.println(v.oldName());

                }

            }

but i don't get anything, here is the output :

[Ljava.lang.reflect.Field;@398f573b
false

I also tried to use refelctions

Reflections reflections = new Reflections("com.pkl.bc.personnaldata.model.Personne");

          Set<Field> annotated = reflections.getFieldsAnnotatedWith(Deprecated.class);

          System.out.println(annotated);

this give me an empty list. here is my annotation :

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface EditColumn {

    String oldName() default "";

    String newName() default "";

    String tableName() default "";
}





Dynamically execute string as code in C#

I need to convert string to executable code. The string is in foreach statement.

foreach (InsuredItem _i in p.InsuredItems)
{
    string formula = "(_i.PremiumRate/100)*SumAssured";
    _i.Premium = (Execute formula);
}

The formula is loaded from setup. this is just a demonstration. I need to execute the string in each loop. Thanks.





C# return a list of all required properties in a class

I'm trying to get a dictionary containing the Property and the DisplayName of all properties in a class that have the Required Attribute.

I'm trying to work off of this extension method that I have but PropertyDescriptor does not contain a definition for Required. Any direction would be appreciated

    public static Dictionary<string, string> GetDisplayNameList<T>()
    {
        var info = TypeDescriptor.GetProperties(typeof(T))
            .Cast<PropertyDescriptor>()
            .ToDictionary(p => p.Name, p => p.DisplayName);
        return info;
    }





jeudi 23 mars 2017

Set property default value before instantiation

I have a class named Student :

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

When I create an instanse of Student class , it is null .

Student s = new Student();

" s.ID is null , s.Name is null and s.Age is null ."

I want to set a default value for Student class , so when I create instanse of it :

Student s = new Student();

" s.ID = 1 , s.Name = Parsa , s.Age = 20 "

In the other word , I want to change declaration or implementation of property getter or override it.

How can I do this ?

Thank you in Advance.





Kotlin Reflection - Set property

I want to inject certain values onto the fields of my target that are annotated with a specific annotation.

I find these fields, I categorize them correctly but when I try to set them I get object is not an instance of declaring class.

When I call my method I already know that the given field is instance of a subtype of Component.
My code is this:

@Suppress("UNCHECKED_CAST")
private fun injectComponent(field: KProperty<*>) {
    val componentType = field.returnType.jvmErasure as KClass<Component> 
    val value = owner.getComponent(componentType) ?: throw InjectionTargetNotFoundException(componentType)

    field.isAccessible = true
    field.call(value)
}

Also it is quite ugly to have that @Suppress("UNCHECKED_CAST"). I just need it because owner.getComponent() expects a KClass<T : Component>.
And it returns the result I expect it to return.





How to Invoke generic method which returns generic type?

Really stuck with this problem,

There are grids at seperate pages and all of them keeps List of objects, all the rows has edit button at the end of the line, and trying to make an dynamic method to return single object when pressed Edit button.

So I add an generic method like this (it might be wrong please correct me), just trying to hit the breakpoint in this method thats why includes nothing inside right now

public T GetItem<T> (int ID) {
       Type _type = typeof(T);
       object result = null;
       //some code
       return (T)result;
}

And the ActionResult calls that GetItem method, ID and TypeName cames from Ajax post, we can assume ID = 7, TypeName = "ProjectViewModel"

public virtual ActionResult GetEditItem(int ID, string TypeName){
        Type _type = Type.GetType("Project.Models." + TypeName); // returns ProjectViewModel
        Type baseService= Type.GetType("Project.Services.BaseService"); // service that keeps the method
        MethodInfo _method = baseService.GetMethod("GetItem");
        object[] item = new object[] { ID }; // parameter to pass the method
        object classInstance = Activator.CreateInstance(_type, null); // create instance with that type (ProjectViewModel right now)
        _method.MakeGenericMethod(_type).Invoke(classInstance, item); // invoke it but it returns error in this line
        return View();
}

Exception is;

An exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll but was not handled in user code

Additional information: Object does not match target type.

Something I miss, what object doesn't match, don't get it. Thanks from now.





Kotlin Reflection - Check if property has type

I want to iterate over all fields in one of my classes, filter for annotated ones and then check if the field has one specific type.
All I found was field.returnType.isSubtype(other: KType) but I don't know how to get the KType of my other class.

Here is my code so far:

target.declaredMemberProperties.forEach {
    if (it.findAnnotation<FromOwner>() != null) {
        if ( /*  it.returnType is Component <- Here I need some working check   */ ) {

            // do stuff
         } else {

            // do ther stuff
         }
    }
}





Use Java Reflections on external JAR file during Maven build

I want to use Reflections to select all classes that have a specific Annotation on them from a JAR file that gets created during a Maven build but I think I am running into an issue to do with the files not being in the classpath since the JAR is create during the Maven build and then my code is also run by Maven but I'm not sure if this is correct OR if it is the issue how to go about fixing it.

When testing my code I just run the file directly in Eclipse and it seems to read the JAR and find the classes ok but when the file is called during a Maven build after the JAR is created I get ClassNotFoundExceptions for each class. This is the code block where I am specifying the JAR file and trying to use Reflections to find the classes in a specific module:

webClasses = new URL("jar", "",
                "file:" + "C:/development/workspaces/trunk/target/http://ift.tt/2nFANi5");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] { webClasses });
reflections = new Reflections(ClasspathHelper.forClassLoader(cl), new TypeAnnotationsScanner(), cl);

Hopefully I explained that ok, should it be possible to call Reflections on a JAR file from a Maven build and for it to actually work?





Checking if a Class?> is instane of other by reflection

I'm trying to create a random generator of any class for stress test purposes.

My generator goals to create any class with default constructor and fill its primitive and String fields (by reflection)

I would like also to fill fields of type Number (Integer, Long, Double....) as they are easily convertible to primitives.

But I couldn't find a simple approach o instanceof between types.

Here is the method

public static <V> Collection<V> createMassiveCollection(Class<V> clazz, int amount, Class<?> collectionType) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

        Random r = new Random();
        RandomGenerator rg = new RandomGenerator();
        @SuppressWarnings("unchecked")
        Collection<V> collection = (Collection<V>) collectionType.newInstance();
        for (int i = 0; i < amount; i++) {
            V item = clazz.newInstance();

            for (Field field : item.getClass().getDeclaredFields()) {

                if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) || java.lang.reflect.Modifier.isFinal(field.getModifiers()))
                    continue;

                field.setAccessible(true);

                if (field.getType().equals(String.class))
                    field.set(item, rg.nextCompliment());

                else if (field.getType().isPrimitive() && (field.getType() != boolean.class && field.getType() != byte.class && field.getType() != char.class))
                    field.set(item, r.nextInt(1000000));

                else {
                    Constructor<?> c = null;

                    try {
                        c = field.getType().getConstructor(String.class);
                    }
                    catch (Exception e) {}
                    if (c != null && Number.class.isInstance(c.newInstance("1")))
                        field.set(item, field.getType().getConstructor(String.class).newInstance(r.nextInt(1000000) + ""));
                }

            }

            collection.add(item);
        }
        return collection;
    }

The third if is the one causing problems I would like something like: "if Type<C> is subtype of Type<V>" but all ways i found need an valid instance of object to check.

ex. Number.class.isInstance(field.getType()) nor field.getType() instanceof Number works because field.getType() is instance of Type.

Does anyone know if it is possible?

Another question (less important) in my method signature i would like to have

Class<? extends Collection<V>> collectionType

but if i do that when i try to call the method like

createMassiveCollection(User.class, 100000, new ArrayList<User>().getClass());

the compiler fails! so, to be able to compile i must trust the user is passing some type that extends Collection as parameter





C# EF Required Attribute not recognized

I am creating an app that uses a database (SQLite). I am using entity framework and ADO.NET to interact with it. I have a seprate Models project in my app that contains all of my Database models.

Now I want to mark some of my class properties as required to reflect the "NOT NULL" option in my database. But if I add the [Required] Attribute from DataAnnotations namespace I get a compiler error saying it cannot be resolved. Here is how my class looks like :

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ReflowModels
{
public class Tag
{
    public Tag()
    {
        this.Options = new HashSet<Option>();
    }
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
    public ICollection<Option> Options { get; set; }
}
}

I have also added a reference to EntityFramework.dll in my project.





How to get name of my manifest resource?

So I'm trying to use the Assembly.GetManifestResourceStream Method (String)

I have my xsd file in one folder nested within some other folder inside my Project.

What exactly is this manifest name and how is it inferred? Is it constructed from the relative path or what?





Cannot convert value of type [[EVObject]?] to expected argument type [_]

I am using Promise Kit for swift 3.0 and I am trying to fulfill my asynchronous network call with the

response.result.value

So I can use it in my ViewController function:

FeedbackServices.getFeedbackSubjects().then { (FeedbackSubject) -> Void in
            print(FeedbackSubject.count)
        }.catch { (error) in
            print(error.localizedDescription)
        }

This is my network layer:

protocol NetworkService
{
    static func GET<T:EVObject>(URL: String, parameters: [String: AnyObject]?, headers: [String: String]?) -> Promise<T>
    static func GET<T:EVObject>(URL: String, parameters: [String: AnyObject]?, headers: [String: String]?) -> Promise<[T]>

}

extension NetworkService
{

    static func GET<T:EVObject>(URL: String,
                    parameters: [String: AnyObject]? = nil,
                    headers: [String: String]? = nil) -> Promise<[T]>
    {

        return Promise { fullFill, reject in

            Alamofire.request(URL,
                              method: .get,
                              parameters: parameters,
                              encoding: URLEncoding.default,
                              headers: headers).responseArray(completionHandler: { response in

                        if (response.result.isSuccess) {

                            fullFill([response.result.value])

                        }else{
                            reject(response.result.error!)
                        }
                  })
            }
    }

When I try to build the project I get the following error:

enter image description here

I am stuck for a few hours now at work and I don't get it working. For any additional information please do not hesitate to ask me!.





Reflections Library to Find All Classes within a Package

I am using the below code to find all of the Classes within a given package name. This works fine when the code is placed directly into my project. However, calling the service from a Commons Jar I put together isn't returning the data from my project. Can this be achieved? I am using org.reflection.Reflections library.

public Set<Class<?>> reflectPackage(String packageName){
    List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    Reflections reflections = new Reflections(
                              new ConfigurationBuilder().setScanners(
                              new SubTypesScanner(false), 
                              new ResourcesScanner()).setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(
                              new ClassLoader[0]))).filterInputsBy(
                              new FilterBuilder().include(FilterBuilder.prefix(packageName))));

    return reflections.getSubTypesOf(Object.class);
}


Project Structure 

Eclipse --- Security Base // Project
        |     |
        |     --- reflectPackage("com.app.controller") call
        |         // Note: this package is within this project, not the Commons project.
        | 
        --- Commons // Project
             |
             --- Reflector // Class
                 |
                 --- reflectPackage // Method





C# Reflection dll but not call constructor? when the constructor need to input parameter

this is my TcpipManager.dll

namespace TCP.QQ
class TcpipManager
{
    public TcpipManager(string ip)
    { 
       //do something with connect device by ip parameter;
    }   
    public bool ChickConnectStatus()
    {
      bool flag = //device connect status;
      return flag;
    }
}

That is my Code to Reflection TcpipManager.dll

Assembly myLibrary = Assembly.LoadFile(fullpath+\TcpipManager.dll");

Type _dllClass = myLibrary.GetType("TCP.QQ.TcpipManager");

object clsInstance = Activator.CreateInstance(_dllClass , new object[] { "192.168.2.7" });

it is working(no show error message and can get its constructor), but it does not connect to the device.

when I import TcpipManager.dll without reflection.

TcpipManager _tt = new TcpipManager("192.168.2.7");

It is working(no show error message and can get its constructor), and It can connect to the device.

why?





mercredi 22 mars 2017

instanceof doesn't work with "or"

I'm working on a web project with Java.

My colleague has finished the socket part, including object serialization and deserialization.

What I need to do is to develop the classes that would be serialized and deserialized to send and receive them.

The sequence diagram is simple:

  • the client sends a string to the server
  • the server create an object with the received string
  • the server sends the object to the client

I have now two kinds of objects:

class T1{public int i1 = 1;}
class T2{public int i2 = 2;}
//both classes have implemented Serializable and override toString

And I do things as below:

Object obj = class.forName(strFromClient).newInstance();
if(obj instanceof T1 || obj instanceof T2)
{
    // send obj to client with my colleague's method
    send(obj);
}

The client can receive successfully the obj of type of T1, the client can System.out.println(obj) and get 1.
To my surprise, when I do the same thing for T2, it doesn't work. When the client try to System.out.println(obj), a 0 is shown whereas I'm expecting a 2. I also try to add a String into T2 and the client get an NullException, meaning that the string in the received obj is null.

I don't quite understand why but if I change my code like this, everything will be fine:

Object obj = class.forName(strFromClient).newInstance();
if(obj instanceof T1)
{
    // send obj to client with my colleague's method
    send(obj);
}
else if(obj instanceof T2)
{
    // send obj to client with my colleague's method
    send(obj);
}





How to rename a String variable dynamically using javassist?

I have a class named sample and I need to rename the variable messageID to NameID such that the corresponding getters and setter are also updated.

public class Sample{
   String messageID;
    public String getMessageID() {
        return MessageID;
    }
    public void setMessageID(String messageID) {
        MessageID = messageID;
    }
}





Comparing type of literal in swift fails?

This code works is Swift 3:

let a = 1
type(of: a) == Int.self // true

However, remarkably this code fails:

// error: binary operator '==' cannot be applied to two 'Int.Type' operands
type(of: 1) == Int.self

What is the syntax to make the second comparison work, if any?

Thanks a lot.





mardi 21 mars 2017

Modifying Android Spinner Dropdown via Reflection - android.widget.Spinner$DropdownPopup cannot be cast to android.support.v7.widget.ListPopupWindow

I have a spinner that I would like the dropdown to always be right-aligned to the spinner itself. I have the following code:

 try {
     Field popup = Spinner.class.getDeclaredField("mPopup");
     popup.setAccessible(true);

     popupWindow = (ListPopupWindow) popup.get(reportList);

     popupWindow.setDropDownGravity(Gravity.END | Gravity.RIGHT);   //requires KitKat or above
     popupWindow.setWidth(measureContentWidth(dataAdapter));
} catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
     Log.e("Exception", e.getMessage());
}

The problem is that setDropDownGravity requires KitKat or above. However, if I change my ListPopupWindow import from android.widget.ListPopupWindow to android.support.v7.widget.ListPopupWindow, I get the following error:

android.widget.Spinner$DropdownPopup cannot be cast to android.support.v7.widget.ListPopupWindow

Is there any way I can set get the dropdown to be right-aligned on devices running Android versions lower than KitKat?





How to get parameter name in aspectj advice class?

I am asking this question with my limited knowledge of java reflection and AOP.

Background:

I am using annotation based advice in my application. Further to get the method parameter which I need to use in my advice I am using spring EL. See below examples: In first example i want to use second parameter to do my work, whereas in second example I am using a POJO and want to use its "id" field.

@MyAnnotation(param = "args[1]")
public void someMethod(int param1, String param2) {
  return null;
}

@MyAnnotation(param = "args[0].id")
public void someMethod(SomeObject someObject) {
  return null;
}

But what I actually want is, to get my hands on the parameter names in my AOP. So that I can use @MyAnnotation(param = "param1") or @MyAnnotation(param = "someObject.id") instead.

From what I have known, you can not get parameter name using reflection. But recently I came across Spring cache abstraction(link), where I see:

@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

Can someone put some light here, how I can achieve similar behavior.





Is reflection giving contradiction in it's answers or have done something wrong?

I'm trying to get all types that implement a particular interface.

Apparently using types.Where(t => typeof(Interface).IsAssignableFrom(t)) was not working so I broke out the problem in to a foreach loop and examined the interfaces for each type using type.GetInterfaces().

So I wrote some code ...

var types = GetSomeTypesFromCurrentAppDomain()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Name.Contains("DataContext"));

var typesWithInterfaces = types.Select(t => new { Type = t, Interfaces = t.GetInterfaces() });
var returnTypes = new List<Type>();

foreach (var t in typesWithInterfaces)
{
    if (!t.Type.IsInterface && !t.Type.IsAbstract && t.Interfaces.Contains(typeof(IDataContext)))
    {
        returnTypes.Add(t.Type);
    }
}

Then I put a few values in the watch window ...

enter image description here

Then I sat there and scratched me head.

Any ideas?





Get class object by name using reflection

Ho to get object by name using reflection? E.g.,

class MyClass {}

MyClass obj = new MyClass();
var tmp = FunctionToGetObjectByItsName("obj");

How to get obj using reflection?

The thing is I want to call method (invoke) and I need somehow to get object by it's name.





How to generate Optional

I want to create JCodeModel for the below method:

private static Optional<Class<?>> getTypeOfId(String fieldName) {
        switch (fieldName.toLowerCase()) {
            case "IDFORCLASSX":
            {
                return Optional.of(X.class);
            }
            default:
            {
                return Optional.empty();
            }
        }
    }

I am presently using below code for creating the return type of the class.

AbstractJClass optionalOfClassType = codeModel.ref(Optional.class)
 .narrow(codeModel.ref(Class.class)
 .narrow(codeModel.ref("?")));

But the above code gives a high priority FindBug error PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS.

Can anyone help me to optimize the above line of code?





instanciate generic Parameter of a class

I have a class

class Holder<SomeType extends AbstractType>{
    SomeType createType(){...}
}

then outside of it, I call

Holder holder = new Holder<MyType>();

I can't figure out how to implements the createType() method.

I tried about everything I could find in StackOverFlow and the web, but I always run in the same dead end : At runtime if I do

TypeVariable typeVariable = getClass().getTypeParameters()[0];
System.err.println("typeVariable "+typeVariable);

I get "SomeType" instead of "MyType", and so I can't fetch the appropriate Constructor since I want to use Class.forName("MyType") and not Class.forName("SomeType") which lead to a java.lang.ClassNotFoundException

I use SomeType extends AbstractType, so I known all my MyTypes will have the same constructor available.

I can't use

ParameterizedType t = (ParameterizedType) MyClass.class.getGenericSuperclass();

since Holder is not a Subclass of anything usefull

I could do something like this in my Holder class, but i'm looking for a way to use reflection without having to pass an argument in the Constructor

private final Class<SomeType> type;

public Holder(Class<SomeType> type) {
    this.type = type;
}

Trying all the various ideas I saw on the net fells like I'm chasing my tail, so I guess I'm missing an obvious element here.

Thanks for your help !





Getting the object with matching classname using Reflection

I am working on a code, where in I am required to read the XML file. I have successfully done it using JAXB, and have successfully maintained it in an object. But my issue is that I will have a hierarchy of class as in

<a>
   <b>12</b>
      <c>
        <d>
          <e>11</e>
        </d>
      </c>
</a>

And the same structure is maintained in the class too. My issue is given the name of the class, will it be possible to extract the object which has already been loaded by XML in the hierarchy? Is is possible through reflection? If so how? And if not is there any work around(as in maintaining any relationship in some file and using that I can directly navigate to the required object). In short I want my code to be dynamic. The purpose of the code is that it will be validating the values in the xml with the values I input. And I can input the values of any node to be validated from a large XML file.





lundi 20 mars 2017

Java Reflection // Can not set java.lang.Boolean to (boolean)true [duplicate]

This question already has an answer here:

I have a class which has a field named "bool" of type java.lang.Boolean and try to set its value via reflection with the following code:

MyClass myClass = new MyClass();
try {
    Field field = myClass.getClass().getField("bool");
    field.setBoolean(myClass, true);
} catch (Throwable ex) {
    ex.printStackTrace();
}

I always get the following error: java.lang.IllegalArgumentException: Can not set java.lang.Boolean field MyClass.bool to (boolean)true

Passing an instance of new Boolean instead of true, Boolean.TRUE, or new Boolean(true).booleanValue() didn't work either. Interestingly, it works flawlessly if I change the type of java.lang.Boolean to boolean. However, I need to be able to process java.lang.Boolean, too.

How can I set a java.lang.Boolean via reflection?





How to test if assembly contains class implementing an interface?

Okay, I'm trying to implement a dynamic module loader for a .NET Core app. The modules are class libraries that may or may not contain a Startup.cs with a class that implements an IModuleInitializer interface. I look through the modules for the initializer class and create an instance of it if it exists. This worked fine until a recent .NET Core update. Now I can't figure out how to test if a type implements the IModuleInitializer interface.

Here's my code:

private static IModuleInitializer CreateModuleInitializer(Assembly assembly)
{
    Type moduleInitializer = null;
    foreach(var type in assembly.GetTypes())
    {
        var interfaces = type.GetTypeInfo().ImplementedInterfaces;
        var interfaceType = typeof(IModuleInitializer);
        var result = interfaces.FirstOrDefault() == interfaceType;
        var result1 = interfaces.Contains(interfaceType);
        var result2 = typeof(IModuleInitializer).GetTypeInfo().IsAssignableFrom(type);
        if (interfaces.Contains(interfaceType))
        {
            moduleInitializer = type;
            break;
        }
    }

    if (moduleInitializer != null && moduleInitializer != typeof(IModuleInitializer))
    {
        return (IModuleInitializer)Activator.CreateInstance(moduleInitializer);
    }

    return null;
}

Here's a screenshot of the values when I debug to a type that implements the interface: enter image description here

And my .NET Core version info in case it helps:

C:\Users\Jason>dotnet --version
1.0.1

C:\Users\Jason>dotnet --info
.NET Command Line Tools (1.0.1)

Product Information:
 Version:            1.0.1
 Commit SHA-1 hash:  005db40cd1

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.14393
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\1.0.1

Any ideas? I'm really hoping I'm just doing something dumb.





Using Scala and reflection to list an array of classes in a package

I have Scala a project directory structure that looks like this:

myapp/
  src/main/scala/
    com/
      me/
        myapp/
          messages/
            BaseMessage.scala
            FizzMessage.scala
          utils
            <omitted for brevity>
          logging
            <omitted for brevity>
          driver
            <omitted for brevity>

Notice the messages package. Currently it only has two classes defined inside of it, BaseMessage (an abstract base class) and FizzMessage (extends BaseMessage). But eventually it will contain hundreds of other classes that are all BaseMessage subclasses.

In my code I have the following:

deviceManager.registerMessage(new FizzMessage())

As I add dozens, possibly hundreds of BaseMessage subclasses to that messages package over time, I would have to add a line of code to "register" each new message type. Subsequently, if I refactor or remove messages I will have to remember to remove their respective line of registration code from above. This will be a pain to manage and I'm wondering if I could just use reflection to scan the messages package for BaseMessage impls, and then subsequently register them:

val messageImpls : Array[T > BaseMessage] = getViaReflection("com.me.myapp.messages")
messageImpls.foreach { msgImpl =>
  deviceManager.registerMessage(msgImpl)
}

Any ideas as to how I could accomplish this?





Idiomatic way to invoke methods through reflection in Kotlin

I have a piece of Kotlin code that is trying to reflectively invoke a method using Java's Reflection package:

val arguments = arrayOfNulls<Any>(numberOfParams)

// Populate arguments

try {
    fooMethod.invoke(fooClass, arguments)
} catch (e: Exception) {
    // Panic
}

It keeps failing with an IllegalArgumentException of "wrong number of parameters".

I did some reading on the issue and it seems the spread operator of the invoke() method refuses to unpack Array<Any> because it's not equivalent to Object[]. I could try to use a standard Object[] from Java, but it makes me wonder, is this the only way? Is it the best way? Is there some way I can do this with Kotlin's types?

What is the most idomatic way to achieve what I want in Kotlin?





Java Reflection : invoking inherited methods from child class

In my application I have following structure :

public class ParentClass{
    public void method1()
    {....}

    public void method2()
    {....}

    public void method3()
    {....}

    public void method4()
    {....}

    public void method5()
    {....}
}

public class ChildClass extends ParentClass{
    public void method3()
    {....}

    public void method4()
    {....}
}


//I have exported the above class in a jar file.
//--------------------XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX---------------------------

public class TestClass{
     public static void main(String args[]) {
        String jarpath = "jar path of the above class"
        File jarFile = new File(jarpath);
        URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()},Thread.currentThread().getContextClassLoader());
        Class<?> dynamicClass = (Class<?>) classLoader.loadClass("packageName.ChildClass");
        Constructor<?> cons = dynamicClass.getConstructor();
        classObject = cons.newInstance();
        Method method = obj2.getClass().getDeclaredMethod("method1",null);
        method.invoke(obj2);
     }
}

In the above call when I invoke the method1 from the object of ChildClass it throws java.lang.NoSuchMethodException.

In actual scenario ParentClass have hundreds on methods which work like main repository and for each Client we create separate ChildClass and override the methods for client specific changes.

Is there any way to invoke the method (which are not overridden) of parent class from the child class object?





Get text property of all forms in an assembly via reflection

I'm trying to iterate over all assemblies in my solution, get all forms and retrieve the text property of each form but I don't really know how to get the value. Here is my code:

 Type formType = typeof(Form);

 var assemblies =
            AppDomain.CurrentDomain.GetAssemblies();

 foreach (var assembly in assemblies)
 {
    var types = assembly.GetTypes();

    foreach (var type in types)
    {
       if (formType.IsAssignableFrom(type))
       {
          var properties = type.GetProperties().Where(x => x.Name == "Text");
       }
    }
 }

I'm not able to retrieve the concrete value of the form text property. I also tried

var property = type.GetProperty("Text").GetValue(???, null);

but don't know how to get the current class. Any ideas? Thank you!





I want to use java reflection to access an object's attrs and values which is automatically filled by Struts2.x in my Action

I want to use java reflection to access an object's attrs and values which is automatically filled by Struts2.x in my Action,but the result is not as I expected,what's wrong?

Here's my Action:

@Controller("custAction")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CustAction extends BaseAction

This is where the method calls:

public String  saveOrUpdate() throws Exception{

    String ret = Constants.STATUS_CUCCESS_JSON;
    try {
        CommonUtil.checkAttr(cust,null,null);

('cust' is a JavaBean)

here's 'cust' value:

'cust' value

log out:

log out

here's my method:

public static void checkAttr(Object vo,String errorMsg,HashMap<String, String> extra) throws IllegalInputException{

    Class<? extends Object> voClass = vo.getClass();
    Field[] field=voClass.getDeclaredFields();
    if(errorMsg==null){
        errorMsg="你的输入包含非法字符,请重新输入!";
    }
    for(Field attr: field){
        attr.setAccessible(true);
        Object value=null;
        try {
            value=attr.get(vo);//获取属性值!!
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("name:"+attr.getName()+"         value:"+value);
        //校验是否有要被区别对待的属性
        /*if(extra!=null&&extra.get(attr.getName())!=null){
            if(value!=null&&checkRegExp(value.toString(),extra.get(attr.getName()))){
                System.out.println("name:"+attr.getName()+"         value:"+value.toString());
                throw new IllegalInputException(errorMsg);
            }
        }else{
            if(value!=null&&checkRegExp(value.toString(),REGEX_INPUT)){
                System.out.println("name:"+attr.getName()+"         value:"+value.toString());
                throw new IllegalInputException(errorMsg);
            }
        }*/
    }

}

Why?Is that Spring cause this problem?