dimanche 30 avril 2017

Creating Subclass via Reflection

I'm trying to create either a subclass of a class, or even just create an instance of that class and override 1 method using reflection.

The class is called EntityRenderer, and i have no other way of accessing it except using reflection. I can access the class fine and create new instances, but i'm not sure how to create a new instance with an overriding method.

As an example. If i was to do this non-reflection i would do something like:

EntityRenderer renderer = new EntityRenderer() {
    @Override
    public void overridenMethod(Parameters) {
        // Handle method
    }
};

My end goal is to change 1/2 variables that are in the method. E.g. double d = 1.0 to double d = 2.0.

I tried to use ClassFileTransformers but for some reason the class i'm looking for is never parsed by the transformer...

I've heard this isn't possible with pure Reflection. As such, i'm willing to use an API such as Javassist to 'assist' with this goal.

Thanks for your help!





Getting a property value using IL for a struct

I'm trying to retrieve a value from the following struct.

public struct T
{
    public string Key { get; set; }
    public string Value { get; set; }
}

using the following code.

var mem = new MemberAccessor(r.GetType(), "Value");
object s = mem.Get(r);

And it works, but it gives me the value of "Key" not "Value". If I try this trying to get the value of "Key" then it gives me a "Cannot read from memory" error.

The following is the creation of the Get delegate used in the above code. This only appears to be a problem with a struct.

    private Func<object, object> GetGetDelegate()
    {
        Type[] setParamTypes = new[] { typeof(object) };
        Type setReturnType = typeof(object);

        Type owner = _targetType.GetTypeInfo().IsAbstract || _targetType.GetTypeInfo().IsInterface ? null : _targetType;
        var getMethod = owner != null
            ? new DynamicMethod(Guid.NewGuid().ToString(), setReturnType, setParamTypes, owner, true)
            : new DynamicMethod(Guid.NewGuid().ToString(), setReturnType, setParamTypes, true);

        ILGenerator getIL = getMethod.GetILGenerator();

        getIL.DeclareLocal(typeof(object));
        getIL.Emit(OpCodes.Ldarg_0); //Load the first argument
        //Cast to the source type
        getIL.Emit(OpCodes.Castclass, this._targetType);

        //Get the property value

        if (IsField(_member))
        {
            getIL.Emit(OpCodes.Ldfld, (FieldInfo)_member);
            if (_memberType.GetTypeInfo().IsValueType)
            {
                getIL.Emit(OpCodes.Box, _memberType);
            }
        }
        else
        {
            var targetGetMethod = ((PropertyInfo)_member).GetGetMethod();
            getIL.Emit(OpCodes.Callvirt, targetGetMethod);
            if (targetGetMethod.ReturnType.GetTypeInfo().IsValueType)
            {
                getIL.Emit(OpCodes.Box, targetGetMethod.ReturnType);
            }
        }

        getIL.Emit(OpCodes.Ret);

        var del = getMethod.CreateDelegate(Expression.GetFuncType(setParamTypes.Concat(new[] { setReturnType }).ToArray()));
        return del as Func<object, object>;
    }





samedi 29 avril 2017

Xamarin.Forms access Binding object data

I want to make a label that will extract the name or some other data of the bound item.

[Display(Description = "Gimme your goddamm first name will ya")]
public string FirstName { get; set; }

Code:

public class TitleLabel : ContentView
{
  public Label Label { get; } = new Label();
  public TitleLabel()
  {
    //TODO ensure Content is not accessed manually
    Content = Label;
  }
  protected override void OnBindingContextChanged() =>
    Label.Text = GetPropertyTitle();


  string GetPropertyTitle()
  {
    var bcp = BindingContextProperty;

    //pseudo:
    var binding = GetBinding(bcp);
    var obj = binding.Object;
    var propertyName = binding.Path;
    var propertyInfo = obj.GetType().GetTypeInfo().DeclaredMembers
      .SingleOrDefault(m => m.Name == propertyName);
    if (propertyInfo == null)
      throw new InvalidOperationException();

    return propertyInfo.GetCustomAttribute<DisplayAttribute>().Description;
  }
}

XAML:

<my:TitleLabel Text="{Binding FirstName}" />

Rendered result:

<my:TitleLabel Text="Gimme your goddamm first name will ya" />





Retrieve the classes used within an instance of a Generic Type using Reflection

Suppose to have a type Pair<K,V> declared in your package. Given an object instance of:

 Pair<Integer, Integer> obj = new Pair<>(1,23);

I want to retrieve the type arguments Integer and Integer to which K and V are respectively associated. By the way, it seems to be that using Java standard reflection I cannot access to the actual class with the instances within Java.

 TypeVariable<? extends Class<?>>[] parameters = obj.getClass().getTypeParameters();

I did not manage to extract such desired information using such parameters. I start to wonder, maybe the type information is kept only at compile time, while at run time the actual type parameter information is removed.





Using reflection and polymorphism with ViewHolder

I have a json with class name, something like this:

{
   "view_class" : "com.view.MyClass"
}

And I have this hierarchy:

    public class Config {
         public String viewClass;
         ...
    }

    public interface ViewHolderInterface {
         void bindValue(...);
    }

    public class SuperMyClass extends RecyclerView.ViewHolder 
implements ViewHolderInterface {
       ... 
    }

    public class MyClass extends SuperMyClass {
       ... 
    }

I read a json file and I generate a "Config" object, so the idea is this:

public void bindViewHolder(SuperMyClass holder, Config config) {

    Class viewHolderClass;

    try {
        //row.viewHolderClass = "com.view.MyClass"
        viewHolderClass = Class.forName(config.viewClass);

    } catch (final Exception exception) {

    }
    // Here I need to "cast" a holder to MyClass and execute the method bindValue.
    final ViewHolderInterface viewHolderInstance =
        (ViewHolderInterface) viewHolderClass.cast(holder);
    viewHolderInstance.bindObjectValue(...);
}

I have tried to do this cast using reflection but I this throws an exception:

java.lang.ClassCastException: SuperMyClass cannot be cast to MyClass

I think that my error is using reflection and the same time try to up-cast, but I have not found another way to do this.

Any idea?





Kotlin check parameter's type

When working with Java's reflection I can do something like this: method.getParameterTypes()[i] which gives me parameter's i type (Class).

How can I achieve this using Kotlin's KCallable? I've tried doing something like this: callable.parameters[i].type but the only thing I found was type.javaType but it returns Type which didn't help me at all. I also tried parameters[i].kind but that didn't help me at all.

How can I do Java's method.getParameterTypes() using Kotlin's KCallable?





vendredi 28 avril 2017

Java reflection handling library changes

Ok so I have an Android app and I started creating an addon system for the app so developers can code content providers that the app can then use to generate different content, I will not go through the whole procedure but everything works fine like so:

1) I created a library called com.myaddonlib that I imported in my project in this library there is an interface and different objects.

2) Now a developer can create a simple Java project on his end, import the library com.myaddonlib, and implement the interface on his main class which have methods that return different objects from the library.

3) Back on the android app, I can load the .jar file created by the developer (after the classes.dex is added to the jar file) and with the android DexClassLoader I can load the implemented interface like so :

DexClassLoader classloader = new DexClassLoader(jarFilePath, tempDirectory, null, context.getClass().getClassLoader());     
Class classToLoad = classloader.loadClass("com.apackage.Addon");

where Addon is the class created by the addon developer that implements the interface from the library residing in a package named com.apackage. I can then cast the interface from the library com.myaddonlib to a new instance of classToLoad and call the functions that the addon developer implemented.

Now here is the issue lets say I decided to update the addon library and remove one of the variables, meaning that the addons object is now different from the object in the updated library. Even when the changed variable is not used something causes the app to crash without any error. Just the fact that both objects are different causes something to malfunction. Now this is not an easy procedure to explain so I would understand that given my bad english some have trouble following. My issue is that I need to know how to avoid this crash due to the change of the library on one of both ends.





Static classes can be used as type arguments via reflection

When trying to use a static class as a type parameter, the C# compiler will throw an error:

var test = new List<Math>();

error CS0718: `System.Math': static classes cannot be used as generic arguments

This has been covered in these questions:

However, I just realized I can create the type via reflection, and the runtime won't complain:

var test = Activator.CreateInstance(typeof(List<>).MakeGenericType(typeof(Math)));

Am I right in concluding this is supported at the CLR level, but not at the language level?

Or is this a gray area in specifications, meaning I should refrain from using these generic constructed types?





Mirror of EKEvent does not show the data

For my EVReflection library I came to a case where a Mirror for an EKEvent did not return any information. Even when going to the complete basics a Mirror did not return anything. When you set a breakpoint at the last line, you will see that there is nothing in the Mirror object. Is this a bug or am I missing something?

    let store = EKEventStore()
    let event = EKEvent(eventStore: store)
    event.startDate = Date()
    event.title = "title"
    event.location = "here"
    event.endDate = Date()
    event.notes = "notes"

    let m = Mirror(reflecting: event)
    print("property count = \(m.children.count)")





Get the type of a closed type from the static constructor of the generic class that the closed type derives from

If I have a generic type with a static constructor and a constrain

interface IMyInterface
{
...
}

class MyGeneric<T> where T : IMyInterface
{
    static MyGeneric()
    {
    ....
    }
}

And a closed type:

class MyClass : MyGeneric<TypeImplementingIMyInterface>
{
    ...
}

Is it possible, through reflection, to retrieve the type of the closed type (MyClass) from within the static constructor in the MyGeneric? If so, how?

I have tried so far without success:

  • var t = typeof(MyGeneric<>);
  • var t = MethodBase.GetCurrentMethod().GetType();

I know I can use the Curiously Recurring Template Pattern to do what I want:

interface IMyInterface
{
}

class MyBase
{

}

class MyGeneric<T1, T2> : MyBase where T1 : IMyInterface, T2 : MyBase
{
    static MyGeneric()
    {
        var t = typeof(T2);
        // ...
    }
}

class MyClass : MyGeneric<TypeImplementingIMyInterface, MyClass>
{
    // ...
}

I would like to know if there is another approach that can be used in the described scenario.

I accept a No as an answer if that is the answer.





How can I do a meaningful java code benchmark with reflection? [duplicate]

This question already has an answer here:

How can I benchmark java reflection methods properly? When I run this the results are very random and inconsistent with the methods Im running it on.

long start = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++) {
    method.invoke(instance, null);
}
System.out.println(System.currentTimeMillis() - start);





PropertyInfo.SetValue - when using in loop <--target exception

i have some problem with Reflection again... I get values from databases (strings). In loop i want to assign values to object.

first i check if class already exists if not i will create her.

                if (exists2 == null)
                {
                    newInstance = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(classFullName);
                }

                else
                {
                    newInstance = exists2;
                }

now i have access to class.

i try to assign to String type value with string

                var newInstanceClassType = Type.GetType(classFullName);
                PropertyInfo pi = newInstanceClassType.GetProperty(newInstancePropertyName);

                if (pi.PropertyType.FullName == "System.String")
                {
                    var stringNewInstance = Activator.CreateInstance(typeof(System.String), new object[] {value.ToCharArray() });
                    //pi.SetValue(stringNewInstance, value, null);
                    pi.SetValue(newInstance, Convert.ChangeType(stringNewInstance,pi.PropertyType), null);
                }

                else
                {
                    pi.SetValue(newInstance, value, null);
                }

and... the first value now is assigned to right property. (everything is ok) but in the second loop it crashes (TargetException was unhandled) Object type is not match with target type

In the loop i only check if object of some class already exists - if exists i dont want to create new object, i want to assign next value to next property

it doesnt matter what i have in both strings, when i change order in database of these strings it again crash at the second string...

any ideas what is wrong here?





jeudi 27 avril 2017

Runtime File Creation

I am trying to create the method named "doit" in runtime using "RuntimeCreation.java" class specified below and append it to my existing class in src/test/java and package com.abc.def.ghi.java(ghi.java is specified at the end of this . ghi.java is already an existing class with some existing methods already already present. I wanted to add this "doit" method to the end of the last method in ghi.class. Please help me to resolve this, i have been struggling very hard to find solution for hsi but couldn't get anything helpful

package com.abc.def.Runtime;

import java.io.*;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

import org.testng.annotations.Test;

public class RuntimeCreation {

  public static void main(String[] args) throws Exception {
    // create the source
    File sourceFile   = new File("Temp/Hello.java");
    FileWriter writer = new FileWriter(sourceFile);

    writer.write(
            " public void doit() { \n" +
            "   System.out.println(\"Hello world\") ;\n" +
            " }"
    );

    writer.close();

    JavaCompiler compiler    = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager =
        compiler.getStandardFileManager(null, null, null);

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                            Arrays.asList(new File("/temp")));
    // Compile the file
    compiler.getTask(null,
               fileManager,
               null,
               null,
               null,
               fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)))
            .call();
    fileManager.close();


    // delete the source file
    // sourceFile.deleteOnExit();

    runIt();
  }

  @SuppressWarnings("unchecked")
  public static void runIt() {
    try {
      Class params[] = {};
      Object paramsObj[] = {};
      Class thisClass = Class.forName("Hello");
      Object iClass = thisClass.newInstance();
      Method thisMethod = thisClass.getDeclaredMethod("doit", params);
      thisMethod.invoke(iClass, paramsObj);
      }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

ghi.java is specified below

package com.abc.def;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EntityUtils;

public class ghi{

    private WebServiceHelper webServiceHelper = new WebServiceHelper();

    public final int ttyHeartBeatWebService(final String sUrl) {
        HttpResponse response = webServiceHelper.invokeGetRequest(sUrl,null);
        int sStatusCode = response.getStatusLine().getStatusCode();
        return sStatusCode;
    }

    public final int bbyMDSWebService(final String sUrl) {
        HttpResponse response = webServiceHelper.invokeGetRequest(sUrl,null);
        int sStatusCode = response.getStatusLine().getStatusCode();
        return sStatusCode;
    }
   ----> "doit" method should be added here 
}





Changing CWD for Method Invoked via Java.Lang.Reflect

I have a Java servlet that uses Reflection to invoke other Java methods. Some Java methods that I invoke generate files, and I want to be able to move those files to another location.

Currently, if an absolute path isn't supplied in the method (e.g. PrintWriter outFile = new PrintWriter("prog.out")), the output file gets thrown into the bin directory of my Tomcat installation.

I've tried setting the CWD with the following code, where myDataDir is the directory I want the output files to go into:

File directory;
directory = new File(myDataDir.getPath()).getAbsoluteFile();
if (directory.exists() || directory.mkdirs()) {
    System.setProperty("user.dir", directory.getAbsolutePath());
}

I've even gone so far as to go into the code for the Java method I've written and print out what "user.dir" is from there. Even there it tells me that everything is set up properly (e.g. "user.dir" == /path/that/i/want). Nevertheless, when I invoke the method with reflection, the output file gets put in the bin directory.

Has anyone experienced anything like this before? Any pointers or guidance would be greatly appreciated.

Some details:

  • Running on Redhat 7.3
  • Using Tomcat version 8.0.36
  • Building with Maven 3.3.9
  • Java 1.7.0

Thanks!





How to access case class field annotation values

I have a case class for which I add some annotation to some of the fields:

final class Anno(min: Int, max: Int) extends StaticAnnotation

case class Test(x: String, @Anno(min = 5, max = 10) y: String)

I would like to iterate each field of the case class, get its value and the case class annotation properties assigned to it (if annotation exists).

Any idea how can it be accomplished in Scala?





Why doesn't my interface have the methods the JLS says it declares?

Reading this part in JLS:

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

I tried to confirm the existence of these methods through reflection, but only the ok method shows up.

Why aren't the implicitly declared methods showing up? How can I see them?

interface C {
    public void ok();
}
public class Test{
    public static void main(String[] args) {
        for (Method m : C.class.getMethods()) {
            System.out.println(m.getName()+":"+Modifier.isAbstract(m.getModifiers()));
        }
    }
}

Output:

ok:true





How to get the value of a Custom Attribute method parameter in C# [duplicate]

This question already has an answer here:

I'm using custom attributes in C#. I can't figure out how to get the value of a method parameter with a custom attribute applied to it.

I call my method like this:

carProcessor(4, "V8");

My method signature looks like:

[CarTypeAttribute("Pontiac")]
public void carProcessor(int doorCount, [CarParamAttribute("EngineType")] string engine)
{
    process();
}

I retrieve it's values via reflection from in the process method:

public void process()
{
    MethodBase method = new StackFrame(1).GetMethod();
    var attributes = method.GetCustomAttributes(true);

    foreach(Attribute attr in attributes){
        Type attrType = attr.GetType();

        if(attrType == typeof(CarTypeAttribute)){
            CarTypeAttribute carAttr = (CarTypeAttribute)attr;
            Console.WriteLine("Found CarTypeAttribute!");
            Console.WriteLine("value" + carAttr.Value);
        }
    }
    //Above works perfect and finds CarTypeAttribute and the value Pontiac

    //Lets get the method parameter attribute
    ParameterInfo[] parameterInfos = method.GetParameters();
    if (parameterInfos.Length > 0)
    {
        for(int j = 0; j < parameterInfos.Length; j++)
        {
            Object[] paramAttributes = parameterInfos[j].GetCustomAttributes(typeof(CarParamAttribute), false);

            if (paramAttributes.Length > 0)
            {
                Console.WriteLine("Parameter " + parameterInfos[j].Position + ", name = " + parameterInfos[j].Name + " has attributes: ");
                //above prints: Parameter 2, name = engine has attributes:
                for(int k = 0; k < paramAttributes.Length; k++)
                {
                    Console.WriteLine("Found it: " + paramAttributes[k]); 
                    //above prints: Found it: CarParamAttribute

                }
                Console.WriteLine("The value for this method parameter is " + ???????); 
                //want above to print that V8 was passed, but don't know how
            }
        }
    }

}

So, I can successfully see that the method has a CarTypeAttribute and that it's value is set to Pontiac. Also I can see that it has a parameter with the CarParamAttribute and it's value is set to EngineType, but I don't know the value of the string parameter passed to the function associated with the CarParamAttribute, which in this case was V8. How do I get that value? If you can't get that, I don't see what the point of being able to apply custom attributes to method parameters is?

Thanks





Dynamic Remote EJB call

I am looking since a long time but actually have not found the correct answer for my case.

General I want to call a remote EJB without knowing all the methodes of it. As far I know, I need to use reflection to accomplish it.

The thing is should I use an interface on client side or not? Normally I use an interface for EJB calls, but I guess I need to use bytecode manipulation to create an dynamic interface at runtime???

Finally the idea is to deploy new applications to the jboss server at runtime (hotdeploy) and call the EJB from the new deployed application via the admin server (main application from the EJB). So I can add/delete/update logic/EJBs during runtime.

But the remote EJB is not every time the same (depends on the task it should execute). So I need to create an interface or class dynamically for each new deployed application/ejb I want to call. Client/admin just know the JNDI name.

Let's assume this is my interface and ejb code from a hotdeployed application. Please consider this is only one EJB out of n.

Remote EJB Interface:

import javax.ejb.Remote;

@Remote
public interface EJBInterface {

    public void www();
    public void store();
}

Remote EJB:

import javax.ejb.Stateless;

import com.xx.yy.EJBInterface;

@Stateless
public class EJBStuff implements EJBInterface{

    @Override
    public void www() {
       //Do some stuff
    }

    @Override
    public void store() {
       //Do some stuff
    }
}

On client/admin side I would like to call the EJB. Should I use an interface or direct a class for the implementation??? Further I assume I need to add a common EJB to each hotdeploy app, which provides me the information from the EJB I want to call so I can create an class or interface at client/admin side.

So does someone has an adivse if I should create an interface on client/admin side or a class and call the EJB without interface view??? To I need another class with provides me the info from the remote EJB???

Thanks in advise.





Getting the name of the variable in a foreach loop

I am trying to get the name of the variables from a List that represents a Value of the dictionary so that i can fill a combo box.So far i have tried using nameof method but i cant't get the name.
In My example i would like to fill the combobox with param1,param2,param3

The const variables are in another class Constants.

        public const string param1 = "a";
        public const string param2 = "b";
        public const string param3 = "c";
        public const string d = "d";
        public const string e = "e";
        public const string f = "f";

The dictionary of lists containing constants

  public static Dictionary<string, List<string>> formIdDict = new Dictionary<string, List<string>>
            {
                {singleParamFo,new List<string> {param1,param2,param3 } },
                {PIDFo,new List<string> {d,e,f } }
            };

The troublesome foreach

public SingleParamForm()
        {
            InitializeComponent();
            foreach (var t in Constants.formIdDict[Constants.singleParamFo])
                singleParamCombo.Items.Add(nameof(t));
        }

What type should i specify in the foreach since i cant use something like

foreach(nameof(var t) in ....)





C# Instantiate a class of any type inside another object and call a method?

apologise in advance if I’m not using correct language here.

I’m learning C# and I’ve got fairly comfortable with threading, locking threads and using ReaderWriterLockSlim. – Purely to indicate a watermark on my learning.

I’m currently trying to write a class that perform EXECUTE-AROUND pattern for any class that is passed to it.

Using rough pseudo code something like this:

class MyWrapperClass(){
    private object containedObject;

    public void importObject<MyObject>();
    {
        where MyObject: new ()
        {
            containedObject = new MyObject();
        }
    }

    public void callMethod(Func<int> MyMethod)
    {
        //Wrapped Code here
        containedObject.MyMethod;
        //Wrapped Code here
    }
}

The objective is that any object type can be passed to my MyWrapper Class – calls to this object can then only be done by via callMethod, the goal is to wrap code before and after MyMethod.

I have seen that I could do this though reflection but that would rely on me passing the method names as strings to the MyWrapperClass and doesn’t seem like the best way to do it.

The goal – is to write agnostic class that handles converting all the methods to new threads, the object would then block any further calls with the wrapped code until the current method is complete.

The purpose – is to quickly turn any object into thread safe action. I’ve done this on per object biases for specific functions, but it would be good to be able to have something that does reasonable amount of housekeeping and not duplicate that code.





Reflection - Java object is not an instance of declaring class

When calling this method, I get a IllegalArgumentException.

public void invoke() throws Exception {
    this.method.invoke(this, parameters);
}

where method is declared in the base class. protected Method method;

I also tried this.method.invoke(this.getClass().newInstance(), parameters);

But none of these work.





Angular2 - How to get properties from class with getter and setter?

I am trying to access class properties and i able to do that. but the problem is i am not able to access get and set method from class.

export class PageModel {
    public ParentID: string = null;
    public Type: string = null;
    public Order: number = 0;

    public get ApplicationManager(): ApplicationManager {
        if (ApplicationManager.Current != null && ApplicationManager.Current.Model != null) {
            return ApplicationManager.Current;
        }
        else {
            return null;
        }
    }

    // Many more methods below.
}

Below is logic for fetching properties from class.

protected GetProperties(obj: any): Array<string> {
    let properties: Array<string> = new Array<string>();

    if (obj != null && typeof obj == "object") {
        for (var property in obj) {
            if (obj.hasOwnProperty(
                 properties.push(property);                    
            }
        }
    }

    if (properties != null)
        properties.sort();

    return properties;
}

In above logic i able to get list of properties but i am not getting get and set method.





Get the Runtime Type of a Generic Type in Scala

I have the following trait:

      trait CSVRowParser[A] {
        def parse(row: Seq[String]): Try[A]
      }

      object CSVRowParser {
        implicit def all[A, H <: HList](implicit gen: Generic.Aux[A, H],
          read: CSVRowReader[H]): CSVRowParser[A] = new CSVRowParser[A] {
          def parse(row: Seq[String]): Try[A] = {
            read.from(row).map(gen.from)
          }
        }
        def apply[A](implicit ev: CSVRowParser[A]): CSVRowParser[A] = ev
  }

I have another class called CSVReader:

class CSVReader[A: CSVRowParser] {

   def parse(path: String): ReaderWithFile[A] = ReaderWithFile[A](path)

   case class ReaderWithFile[B: CSVRowParser](path: String) {
    ...
    // how can I here identify the type of B?
   }

}

I then do the call like this:

  def apply[A: CSVRowParser] = new CSVReader[A]

  val reader = apply[Address]
  val withCustomConfig: Seq[Address] = reader parse "/csv-parser/address.csv" using CSVParserConfig(Pipe)

How can I get the runtime type of A inside the ReaderWithFile case class?





Is that possible to know all the name of derived classes?

Suppose we have a base class and a bunch of derived classes. Is there any way or mechanism to know all the derived class names programmatically?

Maybe reflection is a good idea, but it's not available on C++. I suppose there will be some kind of template that can finish this job during compilation.

class Base{
public:
    virtual void print(){
        // This function should print all the names of derived class.
    }
    virtual Base* getInstance(string class_name){
        // This function should return an instance related to the class name.
    }
};

class Derived_1 : public Base{ // Suppose we have 100 Derived_X classes, 
                 // so we don't want to add its name to a list manually.
};

int main(){
    Base base;
    base.print(); // This should print the name of all the derived class.
    base.getInstance("Derived_1"); // This should return an instance of Derived_1
    return 0;
}





C# set variables from an object using Reflection doesn't work

I want to set variables from an object using Reflection.

For simple object this works. (Propertys)

But objects with class variables (Fields) doesn’t work. Here I get always an Exeption with "The object does not agree with the target type."

Has anyone here an idea how it could go?

namespace Question
{
    class Program
    {
        static void Main(string[] args)
        {
            var genericDataSet = new GenericDataSet<DataObjekt>();
            var returnObjekt = genericDataSet.KeepElementsData();
        }
    }

    public class DataObjekt
    {
        public string Name { get; set; }
        public ObjektData ModelTyp;
        public DataObjekt() { ModelTyp = new ObjektData(); }
    }

    public class ObjektData
    {
        public string Typ { get; set; }
        public string Data { get; set; }
    }

    public class GenericDataSet<T> where T : class, new()
    {
        public T KeepElementsData()
        {
            var item = new T();
            //Propertys durchlaufen
            foreach (var Property in item.GetType().GetProperties())
            {
                item.GetType().GetProperty(Property.Name).SetValue(item, "TestData");  //this works
            }

            //Fields durchlaufen
            foreach (var Field in item.GetType().GetFields())
            {
                foreach (var FieldProperty in item.GetType().GetField(Field.Name).FieldType.GetProperties())
                {
                    var data = item.GetType().GetField(Field.Name).FieldType.GetProperty(FieldProperty.Name);
                    data.SetValue(item, "TestData not work", null); // this doesent work
                }
            }
            return item;
        }
    }
}





Create class when i don't know anything about her

i have problem like this:

In the middle of program i get some class name(as string) and here structure, lets say it can be something like this:

(string) classfullName = myprogram.myclassess.FunnyClass
Properties:
          name=someFirstProperty   Type=System.Int32
          name=someOtherPorperty   Type=System.String

now i would like to create object of this class (i can get here typeof()) but... what should i put in constructor when i don't know how many properties this class would have. i can make that All of the classes which i will operate on would have Constructor with all fields in this case

public FunnyClass(int p1, string p2)

i can make a list of properties of class and FunnyClass would have these 2 properties, but how to make some expression(?) which will call constructors of classes (which i don't know)...?

ps. sorry for my English :)





mercredi 26 avril 2017

Instantiate an instance of a Type including all object properties and adhere to inheritance

I'm not sure if that title is reflective of the actual question, so let me explain. Is there a way to instantiate a class and recursively instantiate all properties that are classes?

For example :

public class Base
{
    public int BaseValue{ get; set;} 
}

public class Extended : Base
{
    public int ExtendedValue{ get; set;}
    public AnotherExtendedClass AnotherClass { get; set;}
}

I would like to create a json payload comprised of an empty instance of Extended with all default values and properties instantiated. And use it like:

string representation = Test.CreateDefaultEmptyJson(Extended);

public static string CreateDefaultEmptyJson(Type type)
{
    JsonSerializerSettings settings = new JsonSerializerSettings().Configure();
    var defaultInstance= Activator.CreateInstance(type);
    return JsonConvert.SerializeObject(defaultInstance, settings);
}

The output does not include the Extended class properties. I get back :

{
    "BaseValue":0
}

When I would really like to see ( or something similar ):

{
    "BaseValue":0,
    {
         "ExtendedValue":0,
         {
             ...
         }
    }
}

I suppose I could recursively iterate all types of Extended and call the default constructor, however, before I go down that road there may be a few lines of code to accomplish the same.





Assigning Object() containing reflected class MyItem objects to reflected class property MyItems()

I've run into an issue where I need to load a class into my code using reflection, create an array of that class, and then assign the array to another reflected object's property.

My minimum example would be:

My DLL:

Public Class MyItem
    Public Property Id As Int32
End Class

Public Class MyMainItem
    Public Property MyItems As MyItem()
End Class

My Test App:

Sub Main()
    Dim myAssembly As Assembly = Assembly.LoadFile("c:\temp\MyDll.dll")
    Dim myMainObject As Object = Activator.CreateInstance(myAssembly.GetType("MyDll.MyMainItem"))
    Dim myItemArray(1) As Object

    myItemArray(0) = Activator.CreateInstance(myAssembly.GetType("MyDll.MyItem"))
    myItemArray(1) = Activator.CreateInstance(myAssembly.GetType("MyDll.MyItem"))

    myMainObject.MyItems = myItemArray
End Sub

The error I receive is InvalidCastException when assigning myItemArray to MyItems:

Conversion from type 'Object()' to type 'MyItem()' is not valid.

Is there a way to make myItemArray be understood as an array of MyItem rather than Object?





How can I get the number of type parameters on an open generic in C#

In short this pretty much explains my problem ...

class Foo<T> { ... }
var type = typeof(Foo<>); <-- runtime provides a RuntimeType object instance in my real code
var paramCount = ((RuntimeType)type).GetGenericParameters().Count; <-- I need this

The problem of course is that "RuntimeType" is an internal type in (I believe) mscorlib, so I can't access it from my code.

Is there another / better way to do this?





Invoke constructor on reflected type with callback of said type

I have a class X with some constructor that has a callback, where the callback passes back the instance of X:

class X
{
    public X(Action<X> callback) { ... }
}

Since I don't have access to the class X (it's protected in another assembly), I'm using reflection to obtain the type and the constructor, so far so good. And don't worry, something like this won't be used in production, it's just for testing purposes.

However, how can I type the callback if I don't have access to X statically? An Action gives casting errors on invocation (understandably). Note I don't actually care about the X type, an object representation is fine.

Thanks





Get Enumvalues via reflection from nested enum in generic class

I need to print out enum values from certain types i accquire through relfection. This works fine mostly. However if the enum is declared within a generic type Enum.GetValues throws the following exception:

[System.NotSupportedException: Cannot create arrays of open type. ]
at System.Array.InternalCreate(Void* elementType, Int32 rank, Int32* pLengths, Int32* pLowerBounds)
at System.Array.CreateInstance(Type elementType, Int32 length) at System.Array.UnsafeCreateInstance(Type elementType, Int32 length)
at System.RuntimeType.GetEnumValues()

Full code for reproduction :

using System;

public class Program
{
    public static void Main()
    {
       var enumType= typeof(Foo<>.Bar);

       Console.WriteLine(enumType.IsEnum);

       foreach(var value in Enum.GetValues(enumType))
       {
           Console.WriteLine(value);
       }
    }

}

public class Foo<T>
{
    public enum Bar
    {
        A = 1,
        B = 2
    }
}

Or test it here

Is this desired behaviour and how do I work arround?

Construction a type would be a workarround but inacceptable for me, since it would ge too complicated.





Attach to a Java process that's running?

I'm trying to attach and call methods and edit variables from a java process that's running from a separate java process.

Example: Process 1 has a loop that prints a String variable that's private and defined in the class. Process 2 (when started), changes the String message and then process 1 will continue to print out the changed variable.

This is more of a simple version of what i'm trying, but if i can figure that out, i can easily find out the rest myself.

Thanks! Erouax





mardi 25 avril 2017

How to await a static async method in a private type?

I'm writing unit tests for a C# app that contains a private nested class. That class in turn defines a static async method I'd like to test:

public class FooClass {
    private static class BarClass {
        public static async Task<string> BazMethod() { }
    }
}

Now it seems I ought to be able to do the following in my test method:

var barClass = new PrivateType(typeof(FooClass).GetNestedType("BarClass", BindingFlags.NonPublic);
var ret = await (Task<string>)barClass.InvokeStatic("BazMethod");

When I run this, barClass is successfully initialized, and in the debugger I can see its DeclaredMethods include {System.Threading.Tasks.Task'1[System.String] BazMethod()}. But the call to InvokeStatic fails with an MissingMethodException: Method Project.FooClass+BarClass.BazMethod not found.

Perhaps because BazMethod is async, its true name for reflection purposes is decorated, and I need to include that decoration in the name passed to the InvokeStatic call?





how to have javadoc available at runtime to use with javascript rhino?

or
how to convert the javadoc at source file into easily readable documentation to help rhino javascript usage?

It should be something I would always run at compile time, to generate help text files to be loaded by my application.

I use Eclipse so where to configure it would be a plus!

It should be easily linkable thru reflection, so the help files identifiers should contain package/class/method/paramIndex.

Not sure but I guess it would be good if it could be a XML file we could dinamically load to link thru reflection.

PS.: I could use annotations: http://ift.tt/2oJdP71
but that would be a lot of work in case I change any parameter name and it's documentation, would have to do it twice, and I would miss the automatic IDE helper when chaging the param var identifier.





How to use C# attributes to select a method in a class based on a string?

Suppose I have a class like this:

public class MyMethods
{

    [SpecialMethod("test")]
    public string GetTestString(int i)
    {
        return string.Format("Hello world {0} times!",i);
    }

    [SpecialMethod("lorem")]
    public string GetSomeLoremIpsumText(int i)
    {
        // ignores the 'i' variable
        return "Lorem ipsum dolor sit amet";
    }

    // ... more methods with the same signature here ...

    public string DefaultMethod(int i)
    {
        return "The default method happened! The attribute wasn't found.";
    }

    public string ThisMethodShouldNotShowUpViaAttributes(int i)
    {
        return "You should not be here.";
    }
}

I also have defined the attribute simply like this:

[AttributeUsage(AttributeTargets.Method)]
public class SpecialMethodAttribute : System.Attribute 
{
    private string _accessor;
    public string Accessor 
    {
        get 
        {
            return _accessor;
        }
    }
    public SpecialMethodAttribute(string accessor)
    {
        _accessor = accessor;
    }
}

What I want to be able to do might look like this:

public class MethodAccessViaAttribute
{
    private MyMethods _m;

    public MethodAccessViaAttribute()
    {
        _m = new MyMethods();
    }

    public string CallMethodByAccessor(string accessor, int i)
    {
        // this is pseudo-code, expressing what I want to be able to do.
        Func<int, string> methodToCall = FindAMethodByAttribute(_m, accessor);
        if (methodToCall == null)
            return _m.DefaultMethod(i);
        else
            return methodToCall(i);
    }

    public void Test()
    {
        // should print "Hello world 3 times!"
        Console.WriteLine(CallMethodByAccessor("test",3));

        // should print "Lorem ipsum dolor sit amet"
        Console.WriteLine(CallMethodByAccessor("lorem",int.MaxValue));

        // should print "The default method happened! The attribute wasn't found."
        Console.WriteLine(CallMethodByAccessor("I-do-not-exist",0));
    }
}

Notice that all methods using the SpecialMethod attribute follow the same method signature. Ideally, the search function would exclude methods not matching the signature, since a try/catch could be used if the method doesn't match the Func signature.

Can I get a point in the right direction for how to accomplish this?





store method in dictionary to execute later given a type

Is it possible to do the following based on a given type:

var myTypes = new List<Type>();//contains list of classes that implements ISameInterface

public class MyType : ISameInterface
{
    public string GetDescription(int num)
    {
    }
}

var result = new Dictionary<Type, Func<int, string>> ();

this is the idea I have but don't really know how to add the expression created to the dictionary

foreach(var t in myTypes)
{
    var exp = Expression.Call(Expression.Constant(Activator.CreateInstance(t),
        t.GetMethod("GetDescription"))
    result.Add(t, exp????);

}





How do you access fields of a static class with reflection?

I have a class like this:

public static class MyThing
{
    public const string MyString = "Hello World!";
    public const int MyInt = 10;
}

Given the strings:

string s1 = "MyString";
string s2 = "MyInt";

How do I access the string "Hello World!" and the int 3? i'm guessing I have to use reflection, but so far have not found anything that works.





Class.getDeclaredMethods() of reflection is returning unwanted values

I have a class A which is a abstract class, class B is concrete and extends A.

Calling B.class.getDeclaredMethods() returns class A's method signatures in addition to class B's but JAVA documentation on getDeclaredMethods() says

"This includes public, protected, default (package) access, and private methods, but excludes inherited methods."

So from above docs i was expecting method foo() which is inherited from abstract parent class should not be returned from getDeclaredMethods() call, but i am getting method foo() which is inherited from abstract parent class is returned from getDeclaredMethods() call.

import java.lang.reflect.*;

public class B extends A {
    public static void main(String[] args) throws Exception {
        Method[] methods = B.class.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            System.out.println(methods[i]);
        }
    }
}


abstract class A {
    public void foo() {
    }
}

Can some one explain me this behavior.





lundi 24 avril 2017

How do I get the "NameOf" on a Foreign Key?

I am running into difficulties when trying to extract the attributes of a property contained in a foreign key attribute. To illustrate, I have these properties in some class

[Required(ErrorMessage = "Please enter value.")]
public long ObjectCatalogId{ get; set; }

[ForeignKey(nameof(ObjectCatalogId))]
public ObjectCatalog ObjectCatalog { get; set; }

I want to find a way to get attributes on ObjectCatalogId property by looking at attributes on ObjectCatalog property. I expect this would mean extracting the name of the Foreign Key (which is ObjectCatalogId), then finding that property in the class ObjectCatalogId and ObjectCatalog both live in and using reflection to get the attributes.

My question is how do I get the name on the Foreign Key?

 attribute.GetType().Name

Doesn't work. Additionally, are there more efficient ways of accomplishing this?





JAVA get all values from Object (recursively)

i created a simple object named UserType.

public class UserType {

  protected Integer id;
  protected Integer accountID;
  protected String prename;
  protected String lastname;
  protected String title;
  protected Gender gender; // Just an Enum (MALE, FEMALE)
  protected String birthday;
  protected String nationality;
  protected List<AddressType> address;
  protected List<BankType> banks; 
}

And I created the AddressType

public class AddressType {

   protected String country;
   protected String zipcode;
   protected String street;
   protected String city;
   protected String housenumber;
   protected String housenumberAddition;
}

And the BankType

public class BankType {

   protected String iban;
   protected String bic;
   protected String bankname;
}

And now i need a function that will show all values recusivly like this

3,
5,
Paul,
Smith,
Dr.,
....
....
[
   {
      DE,
      21225,
      Hogwarts-Street,
      ....
   }
   {
      DE,
      44444,
      Lambda-Street,
      ....
   }
]
... and for BankType ....

I tried to use some Reflectionmethods but it doesnt work for me. I got many problems with this List class ...

I tried this but i cant find a flag to go to the next level....

public void showValues(Object first) {
    int differentValuesCounter = 0;
    Class<?> clazz = first.getClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);

        try {
            Class<?> subClazz = field.getType();
            logger.info(field.getName());
            logger.info(field.get(first).toString());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}





Retrieve the names of all the boolean properties of a class which are true

I have a class that has lots of bool properties. How can I create another property that is a list of strings that contains the name of the properties which have a value of true?

See initial attempt below - can't quite figure out how to filter the true ones

public class UserSettings
{
    public int ContactId { get; set; }
    public bool ShowNewLayout { get; set; }
    public bool HomeEnabled { get; set; }
    public bool AccountEnabled { get; set; }

    // lots more bool properties here

    public IEnumerable<string> Settings
    {
        get
        {
            return GetType()
                .GetProperties()
                .Where(o => (bool)o.GetValue(this, null) == true) //this line is obviously wrong
                .Select(o => nameof(o));
        }
    }
}





How to enumerate constants of a certain type

I'd like to ensure with a test, that for each APIErrorCode constant defined as below, the map APIErrorCodeMessages contains an entry. How can I enumerate all constants of a certain type in Go?

// APIErrorCode represents the API error code
type APIErrorCode int

const (
    // APIErrorCodeAuthentication represents an authentication error and corresponds with HTTP 401
    APIErrorCodeAuthentication APIErrorCode = 1000
    // APIErrorCodeInternalError represents an unknown internal error and corresponds with HTTP 500
    APIErrorCodeInternalError APIErrorCode = 1001
)

// APIErrorCodeMessages holds all error messages for APIErrorCodes
var APIErrorCodeMessages = map[APIErrorCode]string{
    APIErrorCodeInternalError: "Internal Error",
}

I've looked into reflect and go/importer and tried tools/cmd/stringer without success.





dimanche 23 avril 2017

c# reflection - getting list of properties from a PropertyInfo

So, as the heading says, I have an object which is propertyInfo. What I want to get is that property, but I can't seem to find a way to do it.

Firstly I had this method:

public object GetPropertyInfo(object parent, String propertyName)
    {
        object propInf = null;

        PropertyInfo[] propList = parent.GetType().GetProperties();

        foreach (PropertyInfo pInf in propList)
        {
            if (propertyName == pInf.Name)
            {
                propInf = pInf;
            }
        }

        return propInf;
    }

And it works rather well, assuming the supplied 'parent' object is a regular class and not a reflected type.

But some of the properties returned themselves contain properties that I want to access. In these instances, I need to feed the PropertyInfo back into this method and get another PropertyInfo for the property. But if I put a PropertyInfo object into this method, it just returns me a property list of PropertyInfo (as you might imagine).

I have read up on it and it seems that what I may want is the 'GetValue' method of the PropertyInfo class. I'm a little unsure of it though since I can't seem to parse what it is that the method requires.

Even so, I wrote it as such:

public object GetPropertyInfo(object parent, String propertyName)
    {
        object propInf = null;

        object o = null;

        if (parent is PropertyInfo)
        {
            PropertyInfo p = (parent as PropertyInfo);
            o = p.GetValue(p, null);
        }
        else
            o = parent;

        PropertyInfo[] propList = o.GetType().GetProperties();

        foreach (PropertyInfo pInf in propList)
        {
            if (propertyName == pInf.Name)
            {
                propInf = pInf;
            }
        }

        return propInf;
    }

Obviously I hoped the second one would work. It passes through the 'if' statement fine, acknowledging that it is a PropertyInfo type, but then the next part provides an exception which is the following:

TargetException: Object does not match target type.

Maybe I made a mistake with the 'GetValue' since I'm not entirely familiar with it, but if I could do it without specifying a type, that would be great.





c# IList element via reflection

I have a reflected property which is an IList. I have managed to use reflection to get the IList, but now I want to get a list of the properties of one of the elements (any element will do). The attempts I've made so far have failed.

The way I'd handled this before was to use .GetType().GetProperties, but if I try this:

 PropertyInfo[] pi = i[0].GetType().GetProperties();

It doesn't return anything. I know that the item in the list has some properties, but I just can't seem to get a list of them.

'i' is the IList and, if I run the program, it will tell me that it has one object (an instance of an NPC class). It will also give me the details using the intellisense. I just can't seem to get to these details using reflection. Please help!





How to find all the methods of a SetFactoryBean class using javap tool

I am learning java spring framework and came across SetFactoryBean bean in xml configuration file.

There are also targetClass and sourceSet are used in that beam xml file.

I am getting doubt targetClass and sourceSet are part of SetFactoryBean, but I am not able to get all the variables and methods of SetFactoryBean class.

I dont know in which file this SetFactoryBean class is in, but I know where are all these jar files in my system.

Please let me know how do I know variables and methods of SetFactoryBean class using javap tool in my windows system given folder of all files.

I tried the below command

javap -classpath ./spring-core-4.3.5.RELEASE.jar org\springfamework\beans\factory\config\SetFactoryBean

but no use and getting the below error

Error: class not found: org\springfamework\beans\factory\config\SetFactoryBean





EF Core helper method for explicit loading references and collections

EF Core has support for explicit loading. The context has two overloads, one for references and one for collections.

Having two methods is not useful, and gets messy. I want a single method for accepting both as a params array.

So instead of this

await context.Entry(customer).Collection(e => e.Orders).LoadAsync();
await context.Entry(customer).Collection(e => e.Returns).LoadAsync();
await context.Entry(customer).Reference(e => e.Account).LoadAsync();

I want to do this:

await context.Entry(customer).Load(e=>e.Orders, e=>e.Returns, e=>e.Account);

In my context class, I have this so far:

public async Task Load<TEntity, TProperty>(TEntity entity, params Expression<Func<TEntity, object>>[] propertyExpressions)
  where TEntity : class
  where TProperty : class
{

  foreach (var propertyExpression in propertyExpressions) {

    var isCollection = typeof(IEnumerable).GetTypeInfo()
                       .IsAssignableFrom(propertyExpression.Body.Type);

    if(isCollection)
    {
      await Entry(entity)
        .Collection(propertyExpression)     // problem is here !!!!!
        .LoadAsync();
    }
    else
    {
      await Entry(entity)
        .Reference(propertyExpression)
        .LoadAsync();
    }
  }
}

The problem line is shown above. The input is object but .Collection() expects IEnumerable<TProperty>.

How do I make this work?





Why .NET TypeInfo.GetDeclaredField return both public and private fields?

Documentation of TypeInfo.GetDeclaredField method clearly states that it "returns an object that represents the specified public field declared by the current type". So I suppose that it should distinguish by public and non-public fields and return "null" for non-public ones ("the specified field, if found; otherwise, null", according to the docs). However, if I define both public and private fields in the class, a call to GetDeclaredField on the corresponding TypeInfo object returns field object in both cases.

Is this a bug in documentation or a bug in the implementation? I can hardly believe this is an implementation bug since this is the part of core .NET functionality. So why is it documented in such way?





Generics on KProperty1.getDelegate too restrictive?

I am trying to obtain all property delegates of a certain type in a class hierarchy. This is presenting me with some issues. For a start, there seems to be no straightforward way to obtain a class' superclass in Kotlin. The first way I tried was to use Java's Class.getSuperclass:

private fun <T : Any> KClass<T>.getSuperclass(): KClass<in T>? = (java.superclass as? Class<out Any>)?.kotlin as KClass<in T>

But this requires an unchecked cast, because Kotlin will not allow me to convert a Class<in T> back to Kotlin, because apparently in T means it could be something that is not Any, whatever that might be ("Type parameter has an upper bound 'Any' that cannot be satisfied capturing 'in' projection").

So I tried a pure Kotlin solution: First get all superclasses including interfaces (KClass.superclasses) and then filter out every interface. But there is nothing on KClass that tells me if it's an interface! So I have to go to Java for that again. And it again requires an unchecked cast, because for some reason KClass.superclasses is of type List<KClass<*>> and not List<KClass<in T>>:

private fun <T : Any> KClass<T>.getSuperclass123(): KClass<in T>? = superclasses.firstOrNull { it.java.isInterface } as KClass<in T>?

Am I missing something here? I must be.

Now for the actual question, trying to obtain all property delegate instances in a class hierarchy. First I wrote a function to obtain the instances for one class:

private fun <T : Any> KClass<T>.getProperties(obj: T) =
    declaredMemberProperties.also { it.forEach { it.isAccessible = true } }.asSequence().filter { it.getDelegate(obj) is MyPropertyDelegate }

Works fine. But of course I also need all the properties declared in superclasses. So naturally I tried to change the receiver to KClass<in T> which of course results in me not being able to call declaredMemberProperties anymore. How do I solve this?

I already tried using KClass.memberProperties, but it falls short if a subclass overrides a property which is delegated in a parent class. In that case it will only list the overridden property, which does not allow me to access the property delegate instance.





samedi 22 avril 2017

How to create dynamic object for class in java?

Ex:

Element elementInclude1 = doc.createElement("include");
elementMethods.appendChild(elementInclude1);
elementInclude1.setAttribute("name", "T1");

Element elementInclude2 = doc.createElement("include");
elementMethods.appendChild(elementInclude2);
elementInclude2.setAttribute("name", "T2");

Element elementInclude3 = doc.createElement("include");
elementMethods.appendChild(elementInclude3);
elementInclude3.setAttribute("name", "T3");
....

In the above example, number of objects(elementInclude1, elementInclude2,..) created are known dynamically.

No of object required are known in run time, using that value iterating in the loop new object created in each iteration. how can I achieve that.

Need to create objects elementInclude1, elementInclude2, elementInclude3,... dynamically while run time

Just for better understanding I used some wrong practice in the below code.

String noOfObj = 5;
for(int i = 1; i<=noOfObj; i++)
{
Element elementInclude+**noOfObj** = doc.createElement("include");
elementMethods.appendChild(elementInclude+**noOfObj**);
elementInclude+**noOfObj**.setAttribute("name", "T1");
}





In Proxy how to tell if user is expecting promise?

I have setup a proxy like this:

const browser = new Proxy({}, {
    get: function(target, name, receiver) {
        return function(...args) {
            if (userExpectsPromise) { // how to detect this?
                return new Promise(resolve => chrome[name](...args, resolve))
            } else {
                return chrome[name](...args);
            }
        };
        return target[name];
    }
});

What this does is allows user to do browser.***('arg1', 'arg2'), this will call *** on the chrome branch.

However some of the *** on chrome branch accept a final argument of a callback. When it does, a user adds a .then so they would do - browser.***('arg1', 'arg2').then(.....). I need to detect/intercept if user did a .then. Is this possible?

My other option would be to hardcode which chrome.*** accept a callback, but that is not safe way, as the chrome.*** API is always evolving.





Java Reflections failing to get classes that implement an interface

I am sorry if this is a dumb question, but it has been really bothering me for two days and I am trying to figure it out.

I am trying to get all classes that implement an interface named ICommand using the Reflections library. Then, my method for returning the classes returns a Set<? extends ICommand> which I later use a for loop on in another class (Help) and use getDescription() and getCommandName() on each class.

I've tried a few times with some different codes but I am currently getting the exception java.lang.NoClassDefFoundError caused by java.lang.ClassNotFoundException. Keep in mind that the problem occurs at creating a new Reflection instance with the classpath provided inside of the CommandTools class.

I don't know what is causing these problems, I think everything is alright but could there be a problem with the classpath or am I missing something?

Finally, the code:

ICommand Interface

public interface ICommand {

    public void action(MessageReceivedEvent event);

    public String getDescription();

    public String getCommandName();

    public String getUsage();

}

CommandTools class with returnCommands() method

import java.util.Set;

import org.reflections.Reflections;

import com.FatCat.memecat.Core.ICommand;

public class CommandTools {

    public static Set<Class<? extends ICommand>> returnCommands() {
        Reflections reflections = new Reflections("com.FatCat.memecat.Commands");

        return reflections.getSubTypesOf(ICommand.class);
    }
}

A part of the code from the Help class that implements ICommand

    String commandList = "";

    for (Object c : CommandTools.returnCommands().toArray()) {
        commandList = commandList + "`+" + ((ICommand) c).getCommandName() + "` ➤ "
                + ((ICommand) c).getDescription() + "" + "\n";
    }

    event.getTextChannel()
            .sendMessage(Messaging.eBuild(event, "Commands", commandList, ColorList.standard, true))
            .queue((m) -> {
                Messaging.reactions(reactionInfo, 500, m);
            });

Error log

[23:18:07] [Fatal] [JDA]: java.lang.NoClassDefFoundError: com/google/common/base/Predicate
    at com.FatCat.memecat.Functions.CommandTools.returnCommands(CommandTools.java:12)
    at com.FatCat.memecat.Commands.Informative.Help.action(Help.java:24)
    at com.FatCat.memecat.Listeners.CommandListener.onMessageReceived(CommandListener.java:38)
    at net.dv8tion.jda.core.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:329)
    at net.dv8tion.jda.core.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:84)
    at net.dv8tion.jda.core.handle.MessageCreateHandler.handleDefaultMessage(MessageCreateHandler.java:129)
    at net.dv8tion.jda.core.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:50)
    at net.dv8tion.jda.core.handle.SocketHandler.handle(SocketHandler.java:38)
    at net.dv8tion.jda.core.requests.WebSocketClient.handleEvent(WebSocketClient.java:722)
    at net.dv8tion.jda.core.requests.WebSocketClient.onTextMessage(WebSocketClient.java:459)
    at com.neovisionaries.ws.client.ListenerManager.callOnTextMessage(ListenerManager.java:352)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:262)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:240)
    at com.neovisionaries.ws.client.ReadingThread.handleTextFrame(ReadingThread.java:965)
    at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:748)
    at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:110)
    at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:66)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Predicate
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 17 more





Dynymic Runtime Wrapper around multiple objects C#

I'm trying to create a wrapper around multiple objects of different types. The objects are in tools that are attached to displays in order to perform inidivual tasks (like drawing a rectangle ro circle), or peforming some measurements. Each tool lives independently on the display. The user activates the tools by clicking a button where I activate every tool by settings it IsActive property in a for loop inside the button handler.

Since each tool has several properties (which can also change from tool to tool) I was thinking about a dynamic behavior that creates wrapper around a list of tools that automatically creates the properties. I was looking at the ExpandoObject and the DynamicObject, but the problem ist that I can only add properties using the dynamic keyword but I cannot set the properties from the inside by calling TrySetMember explicitly because I'm not able to setup the SetMemberBinder object.

I also want to connect the object to the PropertyGrid to visualize the properties when they have changed.

Attached you can see my currently "achievements", where I have marked the problem with comments.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace WpfApp4
{
    /// <summary>
    /// Wrapper-Object to wrap multiple objects including their properties
    /// and make the object look as if it is a single object.
    /// </summary>
    public sealed class MockObject : DynamicObject, INotifyPropertyChanged
    {
        #region Events 

        /// <summary>
        /// INotiyPropertyChanged-Event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises the property change event.
        /// </summary>
        /// <param name="propertyName_in"></param>
        private void RaisePropertyChanged([CallerMemberName]string propertyName_in = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName_in));
        }

        #endregion

        /// <summary>
        /// Keeps track of properties and values.
        /// </summary>
        private readonly Dictionary<string, object> Properties = new Dictionary<string, object>();

        /// <summary>
        /// Contains the wrapped objects.
        /// </summary>
        [Browsable(false)]
        public ObservableCollection<object> Objects
        {
            get;
            private set;
        } = new ObservableCollection<object>();

        /// <summary>
        /// Creates a new instance of MockObject.
        /// </summary>
        public MockObject()
        {
            Objects.CollectionChanged += Objects_CollectionChanged;
        }

        /// <summary>
        /// Update the wrapper when objects have been added or removed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Objects_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    foreach (object o in e.NewItems)
                    {
                        INotifyPropertyChanged aPropertyChanged = o as INotifyPropertyChanged;
                        if (aPropertyChanged == null)
                            continue;

                        aPropertyChanged.PropertyChanged += APropertyChanged_PropertyChanged;
                    }

                    UpdateProperties();
                    break;

                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    foreach (object o in e.OldItems)
                    {
                        INotifyPropertyChanged aPropertyChanged = o as INotifyPropertyChanged;
                        if (aPropertyChanged == null)
                            continue;

                        aPropertyChanged.PropertyChanged -= APropertyChanged_PropertyChanged;
                    }
                    UpdateProperties();
                    break;
            }
        }

        /// <summary>
        /// Updates properties and values of the wrapper.
        /// </summary>
        private void UpdateProperties()
        {
            Dictionary<string, List<object>> TouchedProperties = new Dictionary<string, List<object>>();

            // Retriebve all property values from all objects
            foreach (object aObject in Objects.ToArray())
            {
                if (aObject == null)
                    continue;

                PropertyInfo[] aProperties = aObject.GetType().GetProperties();

                foreach (PropertyInfo aProperty in aProperties)
                {
                    List<object> Values;
                    if (!TouchedProperties.TryGetValue(aProperty.Name, out Values))
                    {
                        Values = new List<object>();
                        TouchedProperties.Add(aProperty.Name, Values);                        
                    }

                    Values.Add(aProperty.GetValue(aObject));
                }
            }

            // Now clear the old properties and set in the new properties.
            Properties.Clear();

            dynamic ThisObject = this;

            // Only take those values that have an equal amount of objects in the list
            foreach (var aProps in TouchedProperties.ToArray())
            {
                if (aProps.Value.Count != Objects.Count)
                {
                    TouchedProperties.Remove(aProps.Key);
                    continue;
                }

                if (aProps.Value.TrueForAll(o => object.Equals(o, aProps.Value.FirstOrDefault())))
                    Properties[aProps.Key] = aProps.Value.FirstOrDefault();
                else
                    Properties[aProps.Key] = null;

                // Here I fail, I do not know how to create the property
                ThisObject.(aProps.Key) = Properties[aProps.Key];

                // What would help is to use, but I don't know how to create the binder
                this.TrySetMember(/* what the binder?*/, Properties[aProps.Key]);

                RaisePropertyChanged(aProps.Key);
            }
        }

        /// <summary>
        /// React on property changes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void APropertyChanged_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            base.TrySetMember(binder, value);

            if (!Properties.ContainsKey(binder.Name))
                return false;

            foreach (object o in Objects.ToArray())
            {
                o.GetType().GetProperty(binder.Name).SetValue(o, value);
            }

            return true;
        }
    }
}





Why is IllegalArgumentException thrown here by Method.Invoke?

For a programming practical task, we are given an example .class file. We need to print out all methods that take 1 x int input and some printable output, and then allow the user to run that method with one input as given through the command line. However, when I try to invoke the method, an IllegalArgumentException is thrown.

My code that throws the exception:

// Request the user enter an integer and run the requested method.
private static void methodInvoke(Method inMethod, Scanner scanner) throws 
NumberFormatException,IllegalAccessException,InvocationTargetException,InstantiationException,ClassNotFoundException
{
    Integer userNumber = new Integer(0);
    Class methodClass = Class.forName(inMethod.getDeclaringClass().getName());
    Object methodObject = methodClass.newInstance();

    // Debug to confirm only default constructors.
    Constructor constructList[] = methodClass.getConstructors();
    for(Constructor c : constructList)
    { System.out.println(c.toString()); }

    System.out.println("Enter a number to supply to: '" + inMethod.getName() 
                                                        + "(int)':");
    userNumber = Integer.getInteger(scanner.nextLine());

    // Throws IllegalArgumentException here:
    System.out.println(inMethod.invoke(methodObject, userNumber)); 
}

As some fail-safe checks I've done the following:

  • Printed list of constructors to confirm no arguments are required.
  • Printed the integer to confirm scanner reads it correctly.
  • Tested on an example file for which I know the code:

    public class TestFile { public int testMethod(int testInt) { return 2*testInt; } }

Command line output when it occurs:

Enter the name of the class to analyse, excluding '.class':
TestFile
(0): testMethod
Select a method with the method index from above: '(0) to (n-1)':
0
public TestFile() <--- Where I print out the constructors.
Enter a number to supply to: 'testMethod(int)':
1
Error: Invalid argument. <--- Where I catch the exception and print an error message.
java.lang.IllegalArgumentException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at MethodMetrics.methodInvoke(MethodMetrics.java:86)
    at MethodMetrics.main(MethodMetrics.java:30)

Any ideas as to the cause would be appreciated. Am I missing something obvious? :)

I understand similar questions have been asked before, but seemingly cannot nail down the issue in my situation, the others tend to be due to varargs issues.





vendredi 21 avril 2017

How to copy a type from a predefined assembly to a dynamic AssemblyBuilder

I am working on a framework that has some pre-written c# code which ends up in a DLL. I then have another build step in which I want to use Reflection.Emit to generate the rest of the code in the framework.

Using Reflection.Emit, can I copy everything from the original DLL into the new DLL?





How to get value of property in object inside a List

I need to work with properties of objects contained in a List of variable Types, for which i have the following approach using Reflection:

        private System.Data.DataTable ListToDataTable<T>(List<T> L) {

           PropertyInfo[] PIs = typeof(T).GetProperties();

           // Iterating through elements of the List, which are instances of T
           for(int x=0;x<L.Count;x++) {

              Console.WriteLine(PI.GetValue(L[x]).ToString());

           }

        }

I receive a System.Reflection.TargetParameterCountException when executions reaches to try an get the value of said property, it seems this not the appropiate way to get such a property and i know not other ways to do it than Reflection.

Is there another way to do it? Or, which is the proper way to achieve it using Reflection?

Casting, converting or declaring as T before PI.GetValue throws the same Exception.

Thanks in advance.





Write a test to find all types used in the instantiation of a class

I have some code like:

new ValidationFailure<AddSystemUserDto>

This is in various places in my application service layer, I want to find all the different "Dto" types that have been used when newing up a ValidationFailure across the code, is this possible using reflection? Without having to run each application service method?





Entity Framework: Apply filter to a queryable using a propery of known name

I want to use a property of an entity model to filter the result;

This is the code I would normally use:

db.Users.Where(ent => ent.Id > 5).ToList();

But I can only access the property by its name as string ("Id") or by its ProperyInfo.

This is what I tried to use but it doesn't seem to work:

db.Users.Where(ent => (int) ent.GetType().GetProperty("Id").GetValue(ent,null) > 5).ToList();

Note that the where clause might get more complex, and I might use another property type (not int).





Match (formal and actual) type tokens programmtically

In Guava, there is a way to programmatically replace formal type parameters by actual ones: http://ift.tt/2plHmYp . To kind of reverse this, I want to find out how to programmatically match several given types:

TypeToken<?>
        t1 = new TypeToken<List<String>>() {},
        t2 = new TypeToken<List<?>>() {},
        t3 = new TypeToken<List<? extends Number>>() {},
        t4 = new TypeToken<L>() {},
        t5 = new TypeToken<Map<?, ?>>(){},
        t6 = new TypeToken<Map<?, String>>() {},
        t7 = new TypeToken<Integer>(){};

match(t1, t3); // returns null
match(t2, t1); // returns LinkedHashMap(WildcardType(?) => Class<String>)
match(t4, t1); // returns LinkedHashMap(TypeVariable("L") => ParameterizedType(List<String>));
match(t5, t6); // returns LinkedHashMap(
               //   WildcardType(?) => WildcardType(?),
               //   WildcardType(?) => Class<String>
               // )
match(t4, t7); // returns LinkedHashMap(TypeVariable("L") => Class<Integer>);

It should at least return a map of formal type parameters to actual types, if types match, else null. An extension could match subclasses, too. Is there a free implementation that solves this problem?





Place object class instead of generic type

Is it possible to create a List storing elements, which are objects of class of another object? What I mean is: is it possible to make something like that, but with successful compilation?

private SomeRow row = getRow();  // method getRow returns 
                                 // different classes, which extends SomeRow

List<row.class> rows;  // how is it possible to make something like that?

The problem is that in Selenium WebDriver, which I am using, it is impossible to use wildcards, so it is forbidden to do like this List<? extends SomeRow>.

Does anybody have some ideas how to do this? Or tell me if it is impossible at all, please.





Java Create objects with String variable name

I want to create Objects all from the same class, but in a for loop, and each one should get its own variable name from a string.

Can you help me please?

Thanks.





jeudi 20 avril 2017

Calling a generic method with a class constrain in vb.net

Im trying to get the name of a variable in runtime using reflection, i read a lot and find in other question a code in c# for that, now in vb.net the code looks like this

Public Shared Function GetParameterName(Of T As Class)(item As T) As String
    If item Is Nothing Then
        Return String.Empty
    End If

    Return GetType(T).GetProperties()(0).Name
End Function

the problems is when i try to call the function in c# i would be like this where test is the variable

GetParameterName(new {test});

but in Visual im cant call like that and if try like this

GetParameterName({test})

or

GetParameterName(New Object() {test})

the generic method doesn't recognize the variable the properties like name just say "Length" and the value "1"

maybe is a simple thing but i really appreciate your help

Regards





MethodInfo ReflectedType in .NET Core

How can we replace MethodInfo.ReflectedType in .NET Core?

In .NET Core 1.1 MethodInfo.ReflectedType is still unavailable. What is it alternative?





.NET Framework: Get Type from TypeInfo

The new reflection API introduces the TypeInfo class: http://ift.tt/1V61KCF

I can get a TypeInfo instance of a Type (say, a Car) by writing

TypeInfo typeInfo = typeof(Car).GetTypeInfo();

Now, what if I just have a TypeInfo instance, how do I get the Type its refering to? Can I just write

Type type = typeInfo.GetType();

Or will this return a type that is equal to typeof(TypeInfo)?





C# reflection - choosing constructor overload based on available parameters

I've written a generic database class which can be called to carry out common database (CRUD) operations to save re-writing the ADO.NET code in multiple solutions. To make this flexible, there are a number of constructor overloads based on the different database authentication types and instance types etc. The class is as follows:

class Database
{
    // default instance with Windows authentication
    // constructor 1
    public Database(string server, string database, bool persistSecurityInfo)
    {
        _server = server;
        _database = database;
        _persistSecurityInfo = persistSecurityInfo;
        _integratedSecurity = "True";
        _connectionString = "Data Source=" + server + ";Initial Catalog=" + database + ";Persist Security Info=" + persistSecurityInfo.ToString() + ";Integrated Security=True";
    }

    // named instance using Windows authentication
    // constructor 2
    public Database(string server, string instance, string database, bool persistSecurityInfo) : this(server, database, persistSecurityInfo)
    {
        _instance = instance;
        _integratedSecurity = "True";
        _connectionString = "Data Source=" + server + "\\" + instance + ";Initial Catalog=" + database + ";Persist Security Info=" + persistSecurityInfo.ToString() + ";Integrated Security=True";
    }

    // default instance with SQL authentication
    // constructor 3
    public Database(string server, string database, bool persistSecurityInfo, string userName, string password) : this(server, database, persistSecurityInfo)
    {
        _userName = userName;
        _password = password;
        _integratedSecurity = "False";
        _connectionString = "Data Source=" + server + ";Initial Catalog=" + database + ";Persist Security Info=" + persistSecurityInfo.ToString() + ";User ID=" + userName + ";Password=" + password;
    }

    // named instance with SQL authentication
    // constructor 4
    public Database(string server, string instance, string database, bool persistSecurityInfo, string userName, string password) : this(server, database, persistSecurityInfo, userName, password)
    {
        _instance = instance;
        _integratedSecurity = "False";
        _connectionString = "Data Source=" + server + "\\" + instance + ";Initial Catalog=" + database + ";Persist Security Info=" + persistSecurityInfo.ToString() + ";User ID=" + userName + ";Password=" + password;
    }

    private string _server;
    private string _instance;
    private string _database;
    private bool _persistSecurityInfo;
    private string _userName;
    private string _password;
    private string _integratedSecurity;

    private string _connectionString;
    private string _query;

    //CRUD Methods here
}

I have written a console application which is writing to a database. When the application is executed, the user provides some command line switches.

Some of the switches are as follows (There are others relating to the program's operation which I have not included here):

  • /s : database server name
  • /i : database instance name
  • /d : database name
  • /n : integrated security (True or False)
  • /u : db Username
  • /p : db Password

/i, /u and /p are optional (EG if an instance name isn't supplied, the program assumes it is to connect to a default instance on /s)

Therefore, I need the program to, at run time decide which constructor to call based on which arguments have been provided.

pseudo example here

Class Program
{
    static void Main(string[] args)
    {
         foreach (string arg in args[])
         {
             //code to work out which parameters have been provided here and adds them to array. Also other code which checks integrity such as ensuring there is no username without a password and vice versa etc.
             string[] suppliedParameters;

             //if there is a /i , /u , /p parameters, use constructor 4
             //if there is a /u and /p but no /i, use constructor 3
             //if there is an /i but no /u or /n use constructor 2
             //if there is no /i, /u or /n, use constructor 1
         }
    }
}

I know I can use reflection to execute the relevant constructor and that I could achieve selection of the constructor using a switch statement in the Main method which carries out the tests in the logic above but am just wondering if there is a maybe a more elegant way to do this?





Reflection is not working with proguard, when accessing Google AdSize class Fields. Getting NoSuchFieldException

AdSize adSize = (AdSize) AdSize.class.getDeclaredField("BANNER").get(AdSize.class));

and this is the Field declared in AdSize class

public static final AdSize BANNER = new AdSize(320, 50, "320x50_mb");





mercredi 19 avril 2017

Passing a list of Lamba expressions for accessing Properties

I have a static function today that I pass a Property expression and I create a string from it:

public static string SomeFunction<TModel, TProperty>(TModel model, Expression<Func<TModel, TProperty>> expression){...}

I'd like to change it to process a list of expressions like this:

static string SomeFunctionForList<TModel, TProperty>(TModel model, List<Expression<Func<TModel, TProperty>>> expressions){...}

In the second case, I'd loop through the expressions and perform whatever logic I'm doing on them.

This is how I call the function now:

SomeFunction(this, m => m.nameOfProperty)

How would I specify a list of the expressions? I am trying this but it isn't working:

SomeFunctionForList(this,
                    new List<Expression<Func<TModel, TProperty>>> {
                        { m => m.nameOfProperty1},
                        { m => m.nameOfProperty2} 
});

I'm getting a compiler error that TModel and TProperty cannot be found.





Get all annotations of another class inside scala macro annotation

I'm trying to write an annotation for case classes to dynamically add methods for getting MongoDB Document instance. Everything works fine, except the situation of nested case classes:

@MongoEntity
final case class Person(name: String, info: DetailedInfo)

@MongoEntity
final case class DetailedInfo(info: String)

The reason of that is annotations method always return empty collection. In the snippet below accessors method return types using c.typecheck function.

def generateMethods(classType: TypeName, fields: List[ValDef]) = {
  val typedFields = accessors(fields)

  q"""
    ${Modifiers(Flag.IMPLICIT)} def toDoc(model: $classType): org.mongodb.scala.Document = {
      org.mongodb.scala.Document(
        ..${typedFields.map {
          // annotations is always empty =(
          case accessor if accessor.symbol.asType.annotations.exists(_.eq(MongoEntity)) => q"""${accessor.name.toString} -> ${accessor.name}.toDoc(model.${accessor.name})"""
          case accessor if accessor.paramType <:< typeOf[TraversableLike[_, _]] => q"""${accessor.name.toString} -> model.${accessor.name}.toList"""
          case accessor => q"""${accessor.name.toString} -> model.${accessor.name}"""
        }}
      )
    }
   """
}

How can I get the list of annotations of another case class ?





How can Java reflection be used to get the value of a subclass

I'm using reflection to obtain the value of properties within an object. This works fine, however, I am having issues with obtaining the value of properties with objects of the object.

For example: I have object A that has property of type object B, which has a property of type object C. The value that I want exists on object C.

public class A {
 String name;
 B propertyB;
}
public class B {
 String name;
 C propertyC;
}
public class C {
 String className;
 String valueOfInterest;
}

I have tried to use a recursive method to return all the fields of object A and B, but this has not worked for me. I've also tried using:

getValueOfField("valueOfInterest")

public String getValueOfField(String fieldName)
 A a = new A();
 a.getClass().getSuperclass().getDeclaredField(fieldName);

to find the field that the wanted value would exist in, as suggested in Java reflection: Find fields of a subclass but this throws a NoSuchFieldException.





Circular Reference in .Net Assemblies

I am trying to find the dependencies for a set of assemblies at runtime and I noticed that my code is implying that System.dll has a circular reference with System.Configuration.dll. I'm assuming that there isn't actually circular reference between these assemblies but can someone explain why I'm seeing the following results from this code?

var systemAssembly = Assembly.ReflectionOnlyLoadFrom("System.dll");
Console.WriteLine(systemAssembly.GetReferencedAssemblies().Select(a => a.FullName));
// Output:
// mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

var systemConfigurationAssembly = Assembly.ReflectionOnlyLoadFrom("System.Configuration.dll");
Console.WriteLine(systemConfigurationAssembly.GetReferencedAssemblies().Select(a => a.FullName));
// Output:
// mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Note: Assembly paths have been simplified in my example.





Comparing properties, which is usually faster Linq Expressions or Reflection/

This method uses Linq expressions to compare two properties of an IWebElement.

public void CompareProperties<T>(
            IEnumerable<IWebElement> twoElements,
            Func<IWebElement, T> firstvalue,
            Func<IWebElement, T> secondvalue,
            Action<string> NotEqual,
            [CallerMemberName] string Caller = "",
            [CallerLineNumber] int line = 0
            )
        {
            var firstPropertyMethod = firstvalue(twoElements.First());
            var secondPropertyMethod = secondvalue(twoElements.Last());
            var paramExpressionA = Expression.Parameter(typeof(T), nameof(firstPropertyMethod));
            var paramExpressionB = Expression.Parameter(typeof(T), nameof(secondvalue));
            var binaryExpression = Expression.Equal(paramExpressionA, paramExpressionB);
            var invokeEqualityOperator = Expression.Lambda<Func<T, T, bool>>(binaryExpression, paramExpressionA, paramExpressionB).Compile();
            var result = invokeEqualityOperator(firstPropertyMethod, secondPropertyMethod);
            if (!result)
            {
                NotEqual(string.Format("Method {0} Line:{1}", Caller, line));
            }
        }

This method does the same thing using Reflection.

  private List<string> CompareAllProperties(IEnumerable<IWebElement> twoElements)
        {
            var fails = new List<string>();
            var propNames = new List<string> { "By", "Displayed", "Enabled", "Location", "Selected", "Size", "TagName", "Text" };
            propNames.ForEach(prop =>
            {
                var firstElement = twoElements.First();
                var lastElement = twoElements.Last();
                var prop1 = GetPropertyValue(firstElement, prop);
                var prop2 = GetPropertyValue(lastElement, prop);
                if (!prop1.Equals(prop2))
                {
                    fails.Add(prop);
                }
            });
            return fails;
        }

Just wondering if one is majorly faster than the other, and your tips on which is better pattern.





program using reflection run as hadoop jar throws java.lang.NoClassDefFoundError

I have a base and sub class. The requirement is to invoke sub class' method using reflection. Both programs are below.

base.java

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
public class base {
    public static void main(String[] args) {
        URLClassLoader loader = null;
        Class<?> cls;

        try {
            File file = new File("sub.jar" );
            URL[] urls = { file.toURI().toURL() };
            loader = new URLClassLoader(urls);

            cls = loader.loadClass("sub");
            base obj =  (base) cls.newInstance();

            obj.print();

        }
        catch(Exception e) {
            System.out.println("Exception occured:" + e);
            e.printStackTrace();
        }
    }

    public void print() {
        System.out.println("In Base class");
    }
}


sub.java

public class sub extends base {

    public void print() {
        System.out.println("In subclass");
    }
}


compile both in to jars.

javac base.java;
jar cvf base.jar base.class

javac sub.java;
jar cvf sub.jar sub.class

If I invoke the base.jar as "java -cp", it works fine

java -cp base.jar base 
output: "In subclass"

But if I invoke it with "hadoop jar" command, I get

hadoop jar base.jar base

Exception in thread "main" java.lang.NoClassDefFoundError: base
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at base.main(base.java:15)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.lang.ClassNotFoundException: base
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Any help is greatly appreciated.