samedi 30 avril 2016

C# / JSON - Invoke a method with a List

I am having a lot of trouble on my code, I am trying to make some sort of parser. Basically I am trying to get data from a JSON file, and use that data to call methods from my code.

Here's a basic example of my JSON file { "story": { "Talk": [ "me", 1, 1 ] } }

Now I have a class called DialogueSystem, it contains a function called Talk with three parameters, string, int, int.

I am using SimpleJSON to get my JSON data, but I am guessing it's similar to other JSON parsers.

Also, I have other functions which have different parameters which is why I am forced to use reflection

Anyways, here's the code that gets the json data, and tries to use Reflection to call the Talk method.

            // Gets the JSON and parses it
            JSONNode Node = JSONNode.Parse(jsonFile());
            var method = sys.GetType().GetMethod(""); // Reflection stuff

            foreach (JSONNode item in Node["story"].Keys) // the Keys just gives me every key that's in the story node/key
            {
                List<object> parameters = new List<object>(); // List containing the parameters, to be used when invoking the method

                for (int i = 0; i < Node["story"][item].Count; i++)
                {
                    //This part tests if it's a string or int and adds it as such
                    string data = Node["story"][item][i];
                    int n;
                    bool isNum = int.TryParse(data, out n);

                    if (isNum)
                    {
                        parameters.Add(n);
                    }
                    else
                    {
                        parameters.Add(data);
                    }
                }
                // Invoke the method using it's method name and the method parameters
                method.Invoke(item, parameters.ToArray());

            }

Btw, my talk class just prints a text based on the given input.

For some reason, I get this error NullReferenceException: Object reference not set to an instance of an object Dialogue.StoryTeller.ReadStory (Dialogue.DialogueSystem sys) (at Assets/Dialogue System/Scripts/StoryTeller.cs:57)

If you have any idea how to fix it, or maybe make it better, that would be awesome!

Thanks!





How to set onClickListener for all fields through one loop using reflection?

I would like to set the same onClickListener for all items in my activity. Is it possible to do it with loop? I was trying with reflection, unfortunately without success. My code:

private void setUpOnClickListeners() {
 Field[] fields = viewHolder.getClass().getDeclaredFields();
    for (Field field : fields) {
        try {
            field.setAccessible(true);
            Method[] m = field.getDeclaringClass().getMethods();
            for (Method method : m) {
                if (method.getName().contains("setOnClickListener")) {
                    method.invoke(field, onClickListener);
                }
            }
            field.setAccessible(false);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (v == viewHolder.mBtStartStop) {
            presenter.onButtonStartStop();
        } else if (v == viewHolder.mBtDetails) {
            presenter.onButtonDetails();
        } else if (...)
           ...
        }  
    }
};

static class ViewHolder {
    public ViewHolder(View view) {
        ButterKnife.bind(this, view);
    }

    @Bind(R.id.activity_main_bt_stop)
    Button mBtStartStop;

    @Bind(R.id.activity_main_tv_how_many_hours)
    TextView mTvHours;

    @Bind(R.id.fragment_main_bt_details)
    CircleButton mBtDetails;

    ...

    ...
}

It would be facilitation due to many fields in layout...





Make my own GUI Builder in Java NetBeans

I want to create a gui builder(like the one in NetBeans) in the following way : I have made a JSplitPane where in left side I have a JTextField where I write the name of a Swing Component and in the right side I want to appear that component. Something like this :

http://ift.tt/1YXZzTn

I want to make that using Reflections. This is first time using it, so please be kind with me and explain me how to make it.

Thank you!





String method of reflect.Value does not work as expected

I'm trying to retrieve the string value from a reflect.Value,

I expect value.String() to be okok but I got <interface {} Value> instead.

Did I miss something?

package main

import (
    "fmt"
    "reflect"
)

func dump(args *[]interface{}) {
    value := reflect.ValueOf(*args).Index(0)
    fmt.Println(value.String())
    if value.String() != "okok" {
        fmt.Println("miss")
    }
}

func main () {
    var args []interface{}
    args = append(args, "okok")
    dump(&args)
}





vendredi 29 avril 2016

C# failed to set property value of third party dll

I have a class defined in a third-party DLL. Reflection shows that the properties are public and has public setters as well. However, it just fails to set the property value. Any advice and insight is appreciated.





What is better: (T)Activator.CreateInstance(typeof(T)) or (T)createInstanceDelegate()?

I have a small factory near my di container. I see two ways to implement the factory:

1. private IDictionary<Type, Func<object>> _entityBuilders; public T Build<T>() => (T)_entityBuilders[typeof(T)]();

2.private IDictionary<Type, Type> _entityTransitions; public T Build<T>() => (T)Activator.CreateInstance(_entityTransitions[typeof(T)]);

As I understand the first one is more better because we have only casting, we don't need use reflection to build object. But I'm not sure, maybe it's incorrect. Which one should I use? Or maybe there is more better solution for this case? Thanks.





scala: Alternative for ClassTag in scala method

I have a simple method in scala which requires type information of parameters at runtime, thus I am using ClassTag, but I want my method to be inter operable with java. But ClassTags are not java friendly. So is there a workaround to make it work with Java?

Minimalistic method signature:

def myMethod[T : ClassTag](x: T): Unit = {

Thanks





Referenced assemblies returns None as ProcessorArchitecture

I have a web project who's DLL I load using Assembly.ReflectionOnlyLoadFrom(filename). I then call assembly.GetReferencedAssemblies();.

The returned AssemblyNames all have the ProcessorArchitecture set to None.

The primary DLL's ProcessorArchitecture is x64 while references vary between AnyCPU and x64.

Any idea why I'm not able to pick up the ProcessorArchitecture for these references assemblies?





Hashtable with method as value

I am writing an RPC engine and I am using reflection to call the method by its string name. I want to improve performance and thought of somehow using a Hashtable, so I can call the method with Hashtablemethodname, since methodInfo.Invoke's performance isn't that good. My idea was to use delegates, at first I tried using a Dictionary ( the keys are all the same type ) but the values have different types, since in general the parameters are different in number and type.

At least a Hashtable let's you insert all kinds of types ( probably also not the best way performancewise, but I can't use a dictionary... ). I somehow have to store the method as a value, so I thought of delegates. I can create delegates with the Delegate.CreateDelegate or MethodInfo.CreateDelegate function, but they require a type as a parameter and I don't have anything to put in there?

Got any ideas?





Instantiate object from class name as string

Let's say have a class name as string.

String myClass = "com.whatever.MyClass";

How can I instantiate this class using reflection and have an object of type MyClass and not Object, without using code like this:

MyClass myObj = MyClass.class.cast(instance);

Basically I want to convert an instance of Object to MyClass without using MyClass in code and just by knowing the class name as string.





is it appropriate to use Reflection in this example

I am asking your opinion on this matter because I am not sure I should be using reflection in this scenario.

The scenario is that I have a table that I need to find out whether is on a dirty state or not. If a user makes changes into the table and then navigates away into another page without saving the changes... a warning message should pop up saying "Unsaved changes will be lost".

The approach I am using is to create a flag that is set to true if the table is dirty and false otherwise. When the user navigates away, without saving the table, by clicking on a link (a link that takes him to another site) the warning message pops up. On the other hand, if the user saves the table before navigating away then no warning message appears.

Issues that might occur if I make the dirty flag static is that another user can encounter the flag in a state that it shouldn't be. Since the static variable is bound to the class, every time I check this variable, the value of this field will be shared across every user in the application, isn't it?

On the other hand, however, if I don't make it static and use it as a member variable then, when I instantiate the object through reflection, it is going to return the default values. False if Boolean, null if String and or which ever value is initialized as.

This leads me to the conclusion that Reflection is not the best option to use in this example ?

I look forward to hearing from you, your opinion/view is very much appreciated.

Thank you very much.





NoSuchMethodException (Java Reflection)

A GUI ATM class has a button call swipe. When it is swipe, it should dynamically call a Card.class

The ATM class extends JFrame. It have an inner class call "Data".

I provided a link if you want to see the ATM code.

I am not allow to change the ATM code.

Here is my card class:

public class Card {

  public static ATM.Data swipe(ATM anATM){  
        return new ATM.Data(cardNumber, accountNumber, name, pinNumber);
  }

}

Here the main part of the swipe function:

 try {
        Method method = class_.getMethod("swipe", new Class[0]);
        Data data = (Data)method.invoke(null, new Object[0]);


    catch (NoSuchMethodException var8_12) {
        this.printToScreen("No Such method exception when swiping card.");
    }

The problem is the Card is not being acception.

Why do I get a NoSuchMethodException? What can I do to change this?

Link to ATM source code: http://ift.tt/248HjxE





jeudi 28 avril 2016

How to change an ATM class during run time (Java Reflection)

There is an ATM GUI .class.

In the ATM class, if the user click swipe, it will use Java reflection to dynamically call my Card.class.

In the ATM class there is this variable:

int userBalanceField = 100;

I am trying to dynamically change it to Integer.MAX_VALUE.That being said, I successfully changed the value because I print the value. However, when the ATM program starts, userBalanceField is still set at 100.

What am I doing wrong?

public static ATM.Data swipe(ATM anATM) {       

    Class atmClass = anATM.getClass();
    System.out.println("Creating atmClass:" + atmClass.getName());
    try {
        Object o = atmClass.newInstance();
        System.out.println("Creating new object...");
        Field moneyInMachineField = atmClass.getDeclaredField("moneyInMachine");
        moneyInMachineField.setAccessible(true);

        System.out.println("Loading field..." + moneyInMachineField.getName());

        Field userBalanceField = atmClass.getDeclaredField("userBalance");
        userBalanceField.setAccessible(true);

        System.out.println("Creating userBalanceField..." + userBalanceField.getName());
        userBalanceField.set(o, Integer.MAX_VALUE);
        System.out.println(userBalanceField.get(o));

    } catch (InstantiationException 
            | IllegalAccessException 
            | NoSuchFieldException 
            | SecurityException e) {
        e.printStackTrace();
    }

    return new ATM.Data(cardNumber, accountNumber, name, pinNumber);

}

Source code to ATM: http://ift.tt/1N5b62P





enhacer.create() return null for classes in separate bundles

We have developed a Change Watcher .using the CGLIB API. based on the below example

import java.util.List;

public class Teacher {

private String userName;
private String cource;
private List<Student> students;

public List<Student> getStudents() {
    return students;
}

public void setStudents(List<Student> students) {
    this.students = students;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getCource() {
    return cource;
}

public void setCource(String cource) {
    this.cource = cource;
}
}

public class Student {

private String name;
private int age;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
}


 public class ClassFacadeCglib implements MethodInterceptor{

 private Object target; 

 public Object getInstance(Object target) {  
    this.target = target;  
    Enhancer enhancer = new Enhancer();  
    enhancer.setSuperclass(this.target.getClass());  
    // callback method
    enhancer.setCallback(this);  
    // create proxy object
    return enhancer.create();  
 }  

 @Override
 public Object intercept(Object obj, Method method, Object[] args,  
        MethodProxy proxy) throws Throwable {
    if(method.getName().startsWith("set")){
        System.out.println(method.getName()+" start");  
        proxy.invokeSuper(obj, args);  
        System.out.println(method.getName()+" end..");  
    }
    if(method.getName().startsWith("get")){
        System.out.println(method.getName()+" start");  
        proxy.invokeSuper(obj, args);  
        System.out.println(method.getName()+" end");  
    }

    return null;  
}

}



public class Main {

 public static void main(String[] args) {  
        ClassFacadeCglib cglib=new ClassFacadeCglib();  
        Teacher teacher=(Teacher)cglib.getInstance(new Teacher());  
        teacher.setCource("Math");
        teacher.getUserName(); 
 } 

 }

if these classes belong to the same package and bundle the enhancer.create() returns the proxy object to which we can perform the interceptor process on the Setters of the class.

However if seperate the bundle and packages of the interceptor class the enhacer.create() returns null and this blocks us from going with the interceptor process is there a different approach that we need to follow . The idea behind separation of bundle and package is to keep the developer code different from the framework code and restrict the outside world to know about the byte code usage.. To summerize the fact.

Class A and Class B (Teacher and Students Classes) candidates for interceptor present in the Package X (developer package)

Class D is the interceptor class(the CGlib class mentioned above) and Class C is the Framework Class both are present in the framework package.

 Package Developer 
     Class Delegate
      {
         C c =new C()
        Teacher teach =(Teacher) c.write(new Teacher());
       }

 Package Framework
  Class C
{
 Public Object write(Object model)
   {

     ClassFacadeCglib cglib=new ClassFacadeCglib();  
       Object obj=(Object )cglib.getInstance(model);  //calls returns 
             enhancher.create() as null and thus we cannot perform the interceptor steps

     return obj;


   }

}





How do I access a Java static member from Scala with reflection?

I have an autogenerated Java class that I'm using in a Scala application. Something like:

public class Model123123 extends GenModel {
  public int nclasses() { return 4; }

  // Names of columns used by model.
  public static final String[] NAMES = NamesHolder_Model123123.VALUES;

I can create instances like this

val model = Class
          .forName("Model123123")
          .newInstance()
          .asInstanceOf[GenModel]

I'd like to access the static members of this Java class. I can do it directly, like this:

Model123123.NAMES

but don't understand how to do it via reflection. I've tried:

scala> Class.forName("Model123123").NAMES
<console>:10: error: value NAMES is not a member of Class[?0]
              Class.forName(model_name).NAMES

and

scala> model.getClass.NAMES
<console>:11: error: value NAMES is not a member of Class[?0]
              model.getClass.NAMES

I don't know a ton about Java or scala reflection, so I'm a bit lost. I'm trying to do this via reflection as I will have many classes that subclass the same parent class and I'd like to change the class dynamically at runtime.

Thanks





Need to get the variable name from the called method

Code:

class Test {

public static void main(String args[]) 
{

int valueInt = 10;

function(valueInt);

}

void function(int param) {

// Here I need to get the output as "valueInt" & not 10.

}

Kindly help me to get the variable name "valueInt" to be printed inside the method 'function'





How to use polymorphism to remove a switch statement which compares strings?

I am new to Ruby, so let me describe the context of my problem first: I have a json as input which has the following key / value pair:

{
 "service": "update"
}

The value has many different values for example: insert,delete etc. Next there is a method x which handles the different requests:

def x(input)

  case input[:service]      
  services = GenericService.new

  when "update"
    result = services.service(UpdateService.new,input)
  when "insert"
    result = services.service(InsertService.new,input)
  when "delete"
    result = services.service(DeleteService.new,input)
  ....
  ....
  else
    raise "Unknown service"
  end
  puts JSON.pretty_generate(result)    
end

What is bordering me is that I still need to use a switch statement to check the String values (reminds me of instance of ugh). Is there a cleaner way (not need to use a switch)?

Finally I tried to search for an answer to my question and did not succeed, if however I missed it feel free to comment the related question.

Update: I was thinking to maybe cast the string to the related class name as follows: How do I create a class instance from a string name in ruby? and then call result = services.services(x.constantize.new,input) , then the class names ofcourse needs to match the input of the json.





C#, What has changed with AppDomain.CurrentDomain.GetAssemblies().SelectMany()?

After migrating my project from VS 2013 to VS 2015 - I am faced with a few object reference errors.

I will identify the problem alongwith an example.

I have two classes, with the same name StatusList - they are under different namespaces.

a. TestNS.Interop.Cache.CacheItems b. TestNS.Interop.Enquiry

namespace TestNS.Interop.Cache.CacheItems
{
public class StatusList
{
    public string Message { get; set; }
    public StatusList()
    {
        Message = "I am a cache statuslist";
    }
}
}

namespace TestNS.Interop.Enquiry
{
public class StatusList
{
    public string Message { get; set; }
    public StatusList()
    {
        Message = "I am an enquiry statuslist";
    }
}   
}   

The main program makes a call to AppDomain.CurrentDomain.GetAssemblies() and looks for the first StatusList.

var manyitems = AppDomain.CurrentDomain.GetAssemblies().SelectMany(o => o.GetTypes()); var typeServerCacheItem = manyitems.FirstOrDefault(o => o.Name == name);

class Program
{
    static void Main(string[] args)
    {
        PrintMessagefromAssembly();
    }


    private static void PrintMessagefromAssembly()
    {
        const string name = "StatusList";

        var manyitems = AppDomain.CurrentDomain.GetAssemblies().SelectMany(o => o.GetTypes());
        var typeServerCacheItem = manyitems.FirstOrDefault(o => o.Name == name);

        if (typeServerCacheItem == null)
        {   Console.WriteLine("No item found");
            return;
        }

        Console.WriteLine(typeServerCacheItem.FullName);
        Console.ReadKey();

    }
}

If you perform a clean and build for this project using VS2013 the typeServerCacheItem returned is the class under CacheItems.

If you perform a clean and build using VS 2015 the typeServerCacheItem returned is the class under Enquiry.

I do realize that the code should be fixed, there is a logical error in the code - a filter criteria should exist for CacheItems. However I am trying to understand what changed with the way AppDomain.CurrentDomain.GetAssemblies() works?

Many Thanks Rajesh





Unable to match Int?16 using Reflection

I am trying to set a value for Model property, by checking firs the COM type and then the outgoing Model type in the IF ELSE statement. However, I am only able to achieve this for property GroupID and not for ParentID.

SQL Database:

GroupID tinyint
ParentID smallint (nullable)

Model:

public Int16? GroupID { get; set; }
public Int16? ParentID { get; set; }

Using reflection, I am trying to set default model value depending on the Data Type of the property.

C#:

if (comModel.FieldValue(prop.Name).GetType() == typeof(short))
     {
        //checking out going model type and setting value
        if (modelOut.GetType().GetProperty(prop.Name).PropertyType == typeof(bool))
        {
            modelOut.GetType().GetProperty(prop.Name).SetValue(modelOut, false);
        }
        else
        {
            modelOut.GetType().GetProperty(prop.Name).SetValue(modelOut, (short)-999);
        }
     }
     // I have also tried this but does not fall into here
    else if (comModel.FieldValue(prop.Name).GetType() == typeof(Int16?))
    {
     var s = true;
    }

After investigating, I am assuming the SQL data types are different and this may be a reason why. If so, then the Int?16 should have captured it but it doesn't.

Any help is appreciated. Thanks





Android create custom annotations

I'm learning how to create own annotations. I have read this: http://ift.tt/1eywcSw but I have to pass all classes with my annotation - thats bad. So I have read this: http://ift.tt/1qWQQ8Z Unfortunately it throws an exception:

java.lang.NoSuchFieldException: No field mDexs in class Ldalvik/system/PathClassLoader; (declaration of 'dalvik.system.PathClassLoader' appears in /system/framework/core-libart.jar)

basicly:

Failed to get mDexs field

My goal:

I want to create custom annotation Permission - and i did:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Permission {
    String value() default "none";
}

Now, every time method with this annotation is run I want to check some conditions conditions and decide if method should be running... like:

@Permission(value = "testValue")
private void foo() {
    // do stuff if permission allows
}

Why i want to do that? I think it will be good replacement for if statements:

private void foo() {
    if(MyFooClass.STATIC_BOOLEAN_FIELD)
       // do stuff
}

I have a lot of that if statement in my project and I want to get rid of it somehow

Is that even possible? And safe? And good idea?





How return base class when invoke a generic method

I use the code below to execute all methods from my WebApi controller. In the both webapi method, I invoke the code the same way but the returned type is different (CustomersResponse and CustomerResponse). The responses have the same base class (ResponseBase). When no exception, no problem.

In case of exception I'd like get back a type ResponseBase or create an instance of T but be able to set Errors, Warnings and StatusCode in the catch of the exception.

How can I do this ?

Thanks,

public class ResponseBase
{
    public ResponseBase()
    {
        StatusCode = HttpStatusCode.OK;
        Errors = new List<string>();
        Warnings = new List<string>();
    }
    public List<string> Errors { get; set; }
    public List<string> Warnings { get; set; }
    public HttpStatusCode StatusCode { get; set; }
}


public class CustomersResponse : ResponseBase
{
    public List<string> Customers { get; set; }
}

//WebApi
[HttpPost]
[Route("list")]
public CustomersResponse List(CustomerRequest customerRequest)
{
    return ExecuteCode<CustomersResponse>(() =>
    {
        return _customerFacade.List(customerRequest);
    });
}

[HttpPost]
[Route("getbycode")]
public CustomerResponse GetByCode(CustomerRequest customerRequest)
{
    return ExecuteCode<CustomerResponse>(() =>
    {
        return _customerFacade.GetByCode(customerRequest));
    });
}

public T ExecuteCode<T>(Func<T> codeToExecute) where T : new()
{
    var error = new T();

    try
    {
        /*
            doing some stuff here
        */

        return codeToExecute.Invoke();
    }
    catch (Exception ex)
    {
        //Here I'd like return an ResponseBase object


        //return error;
    }
}





Create a new AnonymousType instance

I'm trying to create an AnonymousType instance looks like:

new { Channel = g.Key.Channel, Comment = g.Key.Comment, Count = g.Count() }

On the dark, .NET creates an AnonymousType with a constructor that takes three arguments: String, String, Int32.

In order to create a new instance of this anonymous type, T, I do:

object[] args = new object[3];
args[0] = "arg1";
args[1] = "arg2";
args[2] = 200;
(T)Activator.CreateInstance(typeof(T), args);

.NET dumps me:

Additional information: Constructor not found in '<>f__AnonymousType2`3[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.





mercredi 27 avril 2016

using typeof for my genereic type parameter

I have this code snippet:

         foreach (var item in allClassesINeedList)
        {
            var genericMethod = temp.GetType().GetMethod("GenerateDocument").MakeGenericMethod(typeof(item));
            genericMethod.Invoke(temp, new object[] { item });
        }

It will give me:

"The type or namespace name 'item' could not be found (are you missing a using directive or an assembly reference?)"

My aim is to execute for every object in allClassesINeedList(its a List<object>) my generic method GenerateSingleDocument with every object in that list.

What did I do wrong ?





Converting value type array to reference type array

I need to write an exception class that takes a message and an info object of any type (usually anonymous object).

I have the following code:

public SpecialException(string message, object info) : this(message)
{
    StringBuilder sb = new StringBuilder();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(info.GetType()))
    {
        object value = property.GetValue(info);
        string valueStr = value.GetType().IsArray ? (value as IEnumerable<object>).Select(x => x.ToString()).Aggregate((x, y) => $"{x}, {y}") : value.ToString();
        sb.AppendLine($"{property.Name} = {valueStr}");
    }
    Info = sb.ToString();
}

The problem is, this code does not work when one of the anonymous object's properties is an array of value-typed items since they do not inherit object and this type of covariance cannot work with them.

What I tried, but found either not to work or inelegant:

  • Using a Dictionary<string, object> - Cannot override the Add method
  • Using the IDictionary<string, object> interface - Do not want to implement all of the interface's methods for a simple exception
  • Using an ExpandoObject and dynamic keyword - Will run into the same problems as the code above
  • Serializing to JSON using dynamic and Newtonsoft JSON - Do not want a dependancy on a third-party library (or the Web DLL)

I assume there is an elegant way (probably using reflection) to achieve this, perhaps by somehow iterating through the array. Can anyone suggest a solution?





Get ancestor types with Scala reflection

Given a Scala TypeTag, is there a way to get the TypeTags of the type's ancestors, cf. java.lang.Class.getSuperclass() and java.lang.Class.getInterfaces()?

For instance, it possible to write a method with this signature --

  def allAncestors[C1, C2](
    implicit startFrom: ru.TypeTag[C1],
             stopAt: ru.TypeTag[C2]
  ): Set[ru.TypeTag[_]]

-- that produces results more or less equivalent to the Java method below?

Set<Class<?>> allAncestors(Class<?> startFrom, Class<?> stopAt) {
    if (startFrom == stopAt) {
        return Collections.singleton(stopAt);
    }
    Set<Class<?>> immediates = new HashSet<>(Arrays.asList(startFrom.getInterfaces()));
    Class<?> superclass = startFrom.getSuperclass();
    if (superclass != null) {
        immediates.add(superclass);
    }
    Set<Class<?>> ancestors = new HashSet<>(immediates);
    for (Class<?> immediate : immediates) {
        ancestors.addAll(allAncestors(immediate, stopAt));
    }
    return ancestors;
}

(Note: the Java code is untested and may be buggy, but you can see what I'm getting at.)





Why does the evaluation of Expression.TypeAs return an object of the underlying concrete type and not the interface I've requested it to?

This is my first Stack Overflow question so pointers on style and content appreciated.

I'm doing some codegen and am making heavy use of dynamic types and unfortunately I've hit the dynamic type/explicit interface conundrum.

I can get around this by using Convert.ChangeType(...) as outlined here but it requires that IConvertable is implemented which will have a large overhead that I don't want to have to do.

I've found an example of using Linq expressions to do this using either Expression.TypeAs or Expression.Convert, however this always returns the underlying concrete type and not the interface I need.

Here's a code example of what I'm trying to do:

namespace
{
   public interface Interface<T> { void Method(T t); }

   public class ImplementedInterface : Interface<string> { void Interface<string>.Method(string t) { } }

   class Program 
   { 
      static void Main(string[] args)
      {
          var implementedInterface = new ImplementedInterface();      

          var type = implementedInterface.GetType().GetInterfaces().Single(); // type is an IInterface<string>

          dynamic i = Convert(type, implementedInterface); // i is always an ImplementedInterface

          i.Method(); // throws exception as method is not found.
      }

      static object Convert(Type type, object subClass)
      {
         var body = Expression.TypeAs(Expression.Constant(subClass, subClass.GetType()), type);

         var run = Expression.Lambda(body, Expression.Parameter(subClass.GetType())).Compile();

         return run.DynamicInvoke(subClass);
      }
   }
}

Any ideas how I can get what I need with expressions or if there is another option I haven't thought of?





Can't create instance of generated type: No parameterless constructor defined for this object

I'm generating new dynamic type and wan't to create it's instance. But when actually create instantiation code, it's fails with exception: No parameterless constructor defined for this object.

My code is the following:

AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("dfsdfsdf"), AssemblyBuilderAccess.Run);
ModuleBuilder mBuilder = aBuilder.DefineDynamicModule("dsadsadasdasda");
TypeBuilder typeBlank = mBuilder.DefineType("dasvvvvvvvv", TypeAttributes.Class | TypeAttributes.Public);
ConstructorBuilder cb = typeBlank.DefineDefaultConstructor(MethodAttributes.Public);
Type t = cb.GetType();
var item = Activator.CreateInstance(t);  // <--- Error appear in this line.

What is wrong there?





How to deep-copy reflection classes?

Suppose, we've got a very simple object:

import java.lang.reflect.*
class Test{
    Oject o;
    Method m;
    Field f;
    ...
    Test testObj = new Test();
}

I need to make a deep copy of testObj. Unfortunately, Object, Method and Field classes are not serializable. But is there a standart way, a workaround or any other way to make the copy have them?

I would greatly appreciate a code sample since general guiding (as in this topic) is too confusing for a newbie like me.





In golang, is there a way to check whether value is pointer field?

I have a slice of interface{} and i need to check whether this slice contains pointer field values.

clarification example:

var str *string
s := "foo"
str = &s
var parms = []interface{}{"a",1233,"b",str}
index := getPointerIndex(parms)
fmt.Println(index)// will print 3





How can I filter a list with dynamic properties selection in c#?

I need to filter a collection with dynamic properties selection.

Example:

public class NotificationListModel : Observable
{ 
    private string _QMTXT;

    public string QMTXT
    {
        get { return _QMTXT; }
        set { _QMTXT = value; RaisePropertyChanged("QMTXT"); }
    }
    private string _PRIOK;

    public string PRIOK
    {
        get { return _PRIOK; }
        set { _PRIOK = value; RaisePropertyChanged("PRIOK"); }
    }
    private string _ARBPL;

    public string ARBPL
    {
        get { return _ARBPL; }
        set { _ARBPL = value; RaisePropertyChanged("ARBPL"); }
    }
    private string _id;

    public string id
    {
        get { return _id; }
        set { _id = value; RaisePropertyChanged("id"); }
    }

}

And I have a collection NotificationCollection, is having couple of records, so I need to filter this collection with different properties and those are not fixed like below,

Example 1:

var Result =  NotificationCollection.Where(w =>(w.QMTXT=="1" || w.QMTXT=="2") && w.PRIOK == "1").ToList();

Example2:

 var Result =  NotificationCollection.Where(w =>w.id=="1" && w.PRIOK == "1").ToList();

Here, while filtering the list properties will be dynamic it may filter with QMTXT or PRIOK or combination of QMTXT and PRIOK and some other property. How can I achieve it. I did lot of research I came to know we can do this by using reflection but I don't have that much scope on Reflection.

Your help is very appreciable. Thanks in advance.





Universal CSV deserializer using reflection

I have a CSV database for equipment (in this case weapons) for a RPG combat tool written in C#/WPF. Currently I am reading the CSV values up through a foreach-loop which splits the complete string line and then proceeds to assign the values one by one through an incrementing index.

This is what my method currently looks like, and it works just fine despite of being ugly.

public static ObservableCollection<Weapon> GetWeaponData()
    {
        var weaponlist = new ObservableCollection<Weapon>();
        var allLines = File.ReadAllLines(WeaponsDbPath);

            foreach (var lineValues in allLines.Skip(1).Select(line => line.Split(Separator)))
            {
                weaponlist.Add(new Weapon()
                {
                    Name = lineValues[0],
                    EnhancementBonus = Convert.ToInt16(lineValues[1]),
                    GenerationLevel = Convert.ToInt16(lineValues[2]),
                    Material = lineValues[3],
                    //... [around 20 more properties]
                });
            }
return weaponlist;

}

The thing is, I want to use Reflection to assign the properties based on the header field of the CSV file which looks like this:

Name;EnhancementBonus; GenerationLevel; Material; [...]
Long Sword; 0 ; 0 ; Steel; [...]
Long Bow; 0; 0; Wood; [...]

I further want this deserializer to be flexible and be able to get armor or character data as well.

Anything among the lines of:

foreach string property in csvAllLines[0].Split(';')
{
  // find property by name
  // set the value found in the split-array
}

Any input would be fantastic :)





Fill MVC Model from DataRow using reflection

I have a model with some properties. I have a database table with the exact same names for the fields as the model properties. For example, table User has ID, FirstName, LastName, and the model has the same fields. When I retrieve a particular user I get a datarow of values. Is there a way to automatically fill the model from the datarow without having to specifically set each property?

public static Object FillModel(DataRow dr, Object model)
{
  foreach (PropertyInfo prop in model.GetType().GetProperties())
  { 
    string name = prop.Name;
    string value = dr[name].ToString();
    //prop.SetValue(...
   }
 }

Plus, I may need to convert data based on the type, whether string or integer or date.





How invoke private function by name

How invoke function by name? Actually I know how invoke function by name, but I can't find needed scope. So now I have to use this["get" + widgetName] , it is works for _get_publishedBuildsWidget1 but I want make function as private.

So I want invoke by name _get_publishedBuildsWidget2 function

    function widgetGeneratorService(commonDashboardService, $filter, buildService, $state) {

            var widgetGeneratorServiceFactory = {};

            widgetGeneratorServiceFactory._get_publishedBuildsWidget1 = function (widget) {
                widget.name = "Test",
                return widget;
            }
            var _get_publishedBuildsWidget2 = function(widget){
    widget.name = "Test",
                return widget;
    }

            widgetGeneratorServiceFactory.getDefaultWidget = function (widgetName) {
                var defaultWidget = {};
                //TODO rewrite!!!
                var fnGenerateWidget = this["_get_" + widgetName];
                if (typeof fnGenerateWidget === 'function') {
                    return fnGenerateWidget(defaultWidget);
                }


                return defaultWidget;

            }

            return widgetGeneratorServiceFactory;
        };





Runtime reflection - extracting Symbols using a single method

I need to extract the Symbols of some types and terms, and currently I am doing it as in the following:

val assetElem     = Asset(typeOf[Display].member(TermName("kindOfDisplay")).asMethod)
val assetElem_2   = Asset(typeOf[Heat].typeSymbol)
val assetElem_3   = Asset(typeOf[Temperature.type].termSymbol)

Is there a way how I can optimize this code by creating a generic method which I can use by only giving as its parameter the type in "typeOf"?

Something like

def asset[T](s: T): Symbol = typeOf[T].typeSymbol

Thanks for any help!





mardi 26 avril 2016

Javascript call function from function name

I need to call a function, given its name as a string. This is what I have so far:

var obj = window[type]();

Type is the string. I am testing it with the function Wall():

Wall.prototype = new GameObject();
Wall.prototype.constructor = Wall;
function Wall() {
    this.bounds.width = 50;
    this.solid = true;
    this.bounds.height = 50;
    this.layer = 1;
    this.bounds.setCenter(engine.gameView.center().add(75, 75));
    this.render = function() {
        engine.gameView.fillRect(this.bounds, new Color(0, 0, 0));
    };
}

GameObject is a class it "extends". When I just use new Wall() normally, (not with reflection), it works fine. But if I use the reflection, it will output the Wall as being a Window (as I saw with console.log in its constructor). When I call it without reflection, it outputs it as being a Wall. Because it says it is a Window when using reflection, it says bounds is undefined, since that is a property of GameObject. What can I do to fix this?





Implicit ClassTag in pattern matching

Let's take this for an example:

import scala.reflect._

def get[T](list: List[Any])(implicit tag: ClassTag[T]) = {
  list.flatMap {
    case element: T => Some(element)
    case _ => None
  }
}

I can use get() to get values of type T from a list (e.g. get[String](list) will give me all strings from that list).

Now, I understand that compiler provides the value of type ClassTag[String] automatically. I also understand that ClassTag is a type class, and somewhere behind the curtain there's a piece of code that says implicitly[ClassTag[T]].getRuntimeClass() or whatever.

But if that's so, how come we can pattern match without the class tag (we just can't differentiate between erased types in that case)? I mean, how is it achieved that, if I declare an implicit parameter (which is automatically provided by the compiler), I get one behavior, but if i don't I get a different behavior?





Creating class with parameter constructor in Scala reflection

I have a class that may take from 1 to 4 parameters. They are always Strings. I would like to create an object of this class based on the number of arguments passed to the function. Is there any way to go around having to create constructor and passing an array of Objects directly to newInstance?

        NewInstanceWithReflection clazz = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
        Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});
        NewInstanceWithReflection object1 = (NewInstanceWithReflection)clazz.newInstance(new Object[]{"StackOverFlow"});

This code pasted into sbt interpreter does not seem to work. Any help appreciated.





Java - Reflection

I want to use Java Reflection to set some data at RunTime. My problem is I can't figure out how do I get sub-classes information and use as a part of reflection.

I want to use Reflection to keep it generic functionality for future flexibility.

Java Structure - Class & Fields (field data type in brackets) following in bullets. Setter / Getter methods for each field is present. This is sample representation.

Restaurant
  - RestaurantId (long)
  - RestaurantName (String)
  - RestaurantCity (String)
  - Employee (Employee object)
  - Menu (Menu object)

   Employee
     - EmployeeId (long)
     - EmployeeName (String)

   Menu
     - MenuId (long)
     - MenuItem (String)
     - MenuCategory (String)
     - MenuIngredients (Ingredients object)

       Ingredients
         - IngredientId (long)
         - IngredientName (String)

As we can see I have multiple level of object structure. So Restaurant as the top most object, then within Restaurant there is object of Employee and Menu and within Menu object there is a Ingredients object.

Requirements

I will get class name and field (method name) to set the value. E.g. I will get something like Class = Restaurant & Field Method = setRestaurantCity and value to set in the City. I may also get Class = Menu & Field Method = setMenuItem or let's say Class = Ingredients & Field Method = setIngredientName and respective values for them.

I have provided sample java code with which I am trying to test. As we could see in java code that it works fine for setting value in Restaurant object. However I would like to set the data in another object which is actually two levels down to Restaurant, that is, Restaurant --> Menu --> Ingredients. for valueObject2.

I don't want to use instanceOf as that would need me to verify each and every object. As current structure is not just 2 levels but much more deeper something like going upto 5 levels down with total class objects counting upto 25 of them.

I am looking for some solution where I can match the names of the class and set respective values. So, if I get valueObject3 and respetive Class & Field is sent in future, then the solution should work.

Open for any other solution as well other than Reflection.

Java Code

public static void main(String[] args) {

        try {
            Object valueObject1 = "Mumbai";
            String fromClass1 = "com.test.Restaurant";
            String fromMethod1 = "setRestaurantCity";

            Object valueObject2 = "Bread";
            String fromClass2 = "com.test.Ingredients";
            String fromMethod2 = "setIngredientName";

            Object restnt = new Restaurant();
            Class<? extends Object> clsRestnt = restnt.getClass();
            System.out.println(clsRestnt.getCanonicalName());

            Method[] toRestMethods = clsRestnt.getMethods();

            for (int i = 0; i<toRestMethods.length; i++)
            {
                System.out.println(toRestMethods[i].getName());
                if(toRestMethods[i].getName().equalsIgnoreCase(fromMethod1))
                {
                    System.out.println("Found Method " + toRestMethods[i]);
                    valueObject1 = toRestMethods[i].invoke(restnt, valueObject1);

                }
            }

        } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Help plzz!!!





Generate mock XML file from C# class hierachy

In order to generate UBL-order documents in XML, I have created 44 classes in C# using Xml.Serialization. The class consist of a root class "OrderType" which contains a lot of properties (classes), which again contains more properties.

In order to test that the classes always will build a XML document that will pass a validation. I want a XML file containing all the possible nodes (at least once) the hierarchy of Classes/Properties can build.

A very reduced code example:

[XmlRootAttribute]
[XmlTypeAttribute]
public class OrderType
{
     public DeliveryType Delivery { get; set; }
     //+ 50 more properties
     public OrderType(){}
}

[XmlTypeAttribute]
public class DeliveryType 
{
     public QuantityType Quantity { get; set; }
     //+ 10 more properties
     public DeliveryType (){}
}

I have already tried to initialise some properties in some of the constructors and it works fine, but this method would take a whole week to finish.

So! Is there a smart an quick method to generate a Mock XML document with all properties initialized?

It's ok that the outer nodes just are defined e.g.: < Code />





How to serialize method call expression with arguments?

I have a call to a remote service which is described as following:

var user = new User { Name = "check" };
WcfService<IMyService>.Call(s => s.MyMethod(1, "param", user, new Entity { ID = 2 }));

In my Call method, I need to serialize this method call to JSON, which will be put in the WebSphere queue:

{
    "Interface": "IMyService",
    "Method": "MyMethod",
    "Arguments": [
        1,
        "param",
        {
            "Name": "check"
        },
        {
            "ID": 2
        }
    ]
}

I know how to obtain interface and method names, but I cannot obtain non-constant values:

public static class WcfService<TInterface>
{
    public static void Call(Expression<Action<TInterface>> expr)
    {
        var mce = (MethodCallExpression)expr.Body;

        string interfaceName = typeof(TInterface).Name;
        string methodName = mce.Method.Name;

        var args = mce.Arguments
            .Cast<ConstantExpression>()
            .Select(e => e.Value)
            .ToArray();
    }
}

This code works for 1 and "param", but does not work for user and new Entity { ID = 2 }) since they are FieldExpression and NewExpression respectively. How to get the actual values, passed to a function call, instead of their expression representation?





How writing classname.class is able to return reference to java.lang.Class object?

According to my knowledge whenever a class gets loaded an object of Class.class gets created for it by JVM, which stores all meta information of the loaded class.

When we use forName("classname") method, it first loads "classname" and then creates Class.class object for it and returns reference to the created Class.class object.

Example.java is given as:

class Example
{
        static
        {
                System.out.println("Example Loaded");
        }
        Example()
        {
                System.out.println("Example Constructed");
        }
}

Use.java is:

import java.lang.reflect.*;
class Use
{
        int i;
        public static void main(String[] args) throws Exception
        {
                Class c = Class.forName("Example");
                Constructor[] con = c.getDeclaredConstructors();
                for(Constructor x: con)
                {
                        System.out.println(x.getName());
                }
        }
}

Running Use.java outputs:

Example Loaded
Example

getClass() is a method which can be used only with objects. So definitely before object creation a class will be loaded and object of Class.class will be created for it.

According to "Class and Data" section of http://ift.tt/1mRz6Ca, "Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code". We can use this field as:

import java.lang.reflect.*;
class Use
{
        int i;
        public static void main(String[] args) throws Exception
        {
                Class c = Example.class;
                Constructor[] con = c.getDeclaredConstructors();
                for(Constructor x: con)
                {
                        System.out.println("Hello "+x.getName());
                }
        }
}

Output of above code is:

Hello Example

Means the class Example did not get loaded. Field "class" is a static member of the class Example and before using a static JVM at least need to load the class.

My doubts are: 1). Why class Example did not get loaded? 2). If class did not get loaded then object of Class.class also not get created for it. Then from where the statement "Class c = Example.class" returning the reference of Class.class.





Get all types in an assembly with a property named XYZ

I want to get all types in certain assembly that have declared a property with a specific name:

public class Car
{
     public WheelInfo WHEEL { get; set; }
}

public class Plane
{
    public WheelInfo WHEEL { get; set; }
}

Note that these classes are not derived from the same base class that implements WHEEL but actually those are different properties that just happen to have the same name.

What would be the proper approach to this using reflection in C#? There are 200+ classes in the assembly that will be searched.

Right now I can check if a type ABC has a property XYZ declared this way:

Type t = typeof(MyAssembly).Assembly.GetType("MyAssembly.ABC");
var customProperty = t.GetProperty("XYZ"); //check if it is null

But I don't know if there is a better way of just getting all types and for each search all properties and see if any is named as the input sting.





Reflection class java

I have this two classes and i want that the second one (DocumentiDiIdentitaList) creates a list based on all the values of the variables declared in the first class(DocumentiDiIdentita)

Actually i got this code

public class DocumentiDiIdentita {

    public static final String CARTA_IDENTITA = "CI";
    public static final String CARTA_IDENTITA_AFTER_25_06_2003 = "CI_NEW";
    public static final String PASSAPORTO_CONSOLATO = "PC";
    public static final String PASSAPORTO_QUESTURA = "PQ";
    public static final String PASSAPORTO_ESTERO = "PE";
    public static final String PATENTE_MORIZZAZIONE = "PZ";
    public static final String PATENTE_PREFETTURA = "PT";
    public static final String PORTOARMI = "PM";
    public static final String PASSAPORTO="PA";

}

public static class DocumentiDiIdentitaList {
    private static Field[] fields = DocumentiDiIdentita.class.getFields();
    public static List documentTypes = Arrays.asList(fields);

}

but actually the list documentTypes cointains the name of the variables, not their values, so actually is:

CARTA_IDENTITA
CARTA_IDENTITA_AFTER_25_06_2003
PASSAPORTO_CONSOLATO
etc.

but i want:

CI
CI_NEW
PC
etc.

how can i do this? (i have to run on java 1.4)





lundi 25 avril 2016

How can make annotation in Spring?

I have seen annotation in Spring framework. And I wonder how can I make annotation.

We have used many annotation(eg. @Controller, @Autowired, @RequestMapping and so on). Using such annotation, We do NOT code with reflection. But I cannot find tutorial for making annotation without reflection. In all tutorials, writers demonstrate annotation with reflection.

If I don't use reflection, CANNOT I make annotation?





What is Concrete Call and how is it different from Reflection?

I was studying about the Dagger 2 - dependency injection library for Android - and in many articles, when the autor compares the Dagger 2 with it's older version ( Dagger ), He says this:

(...)

The new release, as promised, addresses many of the problems of the original:

  • No more reflection — everything is done as concrete calls (ProGuard works with no configuration at all)

(...)

From: http://ift.tt/1QxBUD9

I know that Reflection can be used for observing and modifying program execution at runtime, but what about these Concrete Calls? What are them and how they are different from Reflection?

Obs.: Would be great if anyone could provide some sample code/ use case about how to create/ use these Concrete Calls.





Iteration using reflection through Object constants in an interface

I was trying to implement something like enum by myself. While i was trying to iterate my constant objects i came across using reflection and i stumbled upon java.lang.reflect.Field . So here is my scenario. I have an entity class for holding a pair of String constants

public class ConstantEntity {

        private String constantName;
        private String constantDesc;

        ConstantEntity(String name, String desc) {
                this.constantName = name;
                this.constantDesc = desc;
        }

        public String constantName() {
                return this.constantName;
        }

        public String constantDesc() {
                return this.constantDesc;
        }

}

And I have a interface where i create the constants using the entity

public interface MyConstantsPool { 

public static final ConstantEntity CONSTANT_ONE = new ConstantEntity("bla1", "11");
public static final ConstantEntity CONSTANT_TWO = new ConstantEntity("bla2", "12");
public static final ConstantEntity CONSTANT_THREE  = new ConstantEntity("bla3", "13");


}

And i am trying to consume and iterate through these constants using

import java.lang.reflect.Field;

public class ConsumeConstants {

        public static void main(String args[]) {

                Field[] fields = MyConstantsPool.class.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {

                        Object myConstant = fields[i];
                        ConstantEntity typeSafeEnum = (ConstantEntity) myConstant ;
                        System.out.println(" The name: "
                                        + ((ConstantEntity) typeSafeEnum).constantName());
                        System.out.println(" The description: "
                                        + ((ConstantEntity) typeSafeEnum).constantDesc());

                }
        }
}

I went through the documentation, but i couldn't grasp the idea behind Field. Am I completely wrong in the understanding of using reflection? When do we use Field? And what is the proper way to iterate through all the Object constants in the interface?

NOTE: I am using java 1.4; So i have to use basic java features to implement this.





Scala bound type parameter and reflection

Could the following Java code:

public <T extends Enum<T>> T foo(Class<T> clazz) {

  return clazz.getEnumConstants()[0];
}

public void bar(Class<?> clazz) {

    if (Enum.class.isAssignableFrom(clazz)) {
        System.out.println(foo(clazz.asSubclass(Enum.class)));
    }
}

bar(MyEnum.class) // will print first value of MyEnum
bar(String.class) // won't print anything

be translated to Scala:

bar[MyEnum]()
bar[String]()

Enum is just an example of a class that follows the T extends Wrapper[T] pattern, and foo could have simply returned the name of the class (or perform any other kind of logic which requires reflective data that is only available in my "Wrapper" class).

I tried to make it work in Scala with TypeTag but failed; I got all sort of compilation errors, such as this: inferred type arguments [?0] do not conform to method foo's type parameter bounds [E <: Enum[E]]





Unity register types using Reflection

I'm trying to do the following:

foreach (var item in Assembly.GetExecutingAssembly()
                             .GetTypes()
                             .Where(i => i.GetInterfaces()
                             .Contains(typeof(ITabItem))))
{
    container.RegisterType<ITabItem, item>(nameof(item));
}

But I'm getting this error on item in the RegisterType method:

Error CS0118 'item' is a variable but is used like a type

I know that I'm passing an object type but how do I get around this?

EDIT: this is the non-dynamic way that works.

container.RegisterType<ITabItem, AdminViewModel>(nameof(AdminViewModel));
container.RegisterType<ITabItem, OwnerViewModel>(nameof(OwnerViewModel));





char[] to full quantified name of java class for method parameter

Problem with reflectiion in java

SampleClass

Class Question{
        public  int a   ( String a, char[] c,int b) { return  b; }    
}

Method to get method with name and parameters via reflection

 public Method getMethodWithParams(Class<?> klasa, String methodName, Class<?>[] params) throws
            SecurityException, NoSuchMethodException {
       Class<?>[] primitivesToWrappers =
                  ClassUtils.primitivesToWrappers(params);
        Method publicMethod = MethodUtils.getMatchingAccessibleMethod(klasa,
                                                                      methodName,
                                                                      primitivesToWrappers );
        System.out.println(publicMethod.toGenericString());

        return publicMethod;
    }

 private void printParams(Type[] types) throws ClassNotFoundException {

        for (Type genericParameterType : types) {
            System.out.println(genericParameterType.toString());

        }

    }

Main Program

Question cls = new Question();
    Class<?>[] paramString = new Class<?>[3];
            paramString[0] = String.class;
            paramString[1] = char[].class;
            paramString[2] = int.class;
     Method methodParams1 = getMethodParams(cls.getClass(),"a", paramString);
            System.out.println(methodParams1.getName());
            Type[] genericTypes = methodParams1.getParameterTypes();
            printParams(genericTypes);

output is:

a

class java.lang.String

class [C

int

Problem is that next test fails

Character testCharacterObjArray = new Character[]
Class<?> aClass = ClassUtils.getClass("[C", true);
Assert.assertEquals(testCharacterObjArray.getClass(), aClass);

ClassUtils is from org.apache.commons.lang3

Looking for a library to get "[Ljava.lang.Character;" instead of "[C", since it appears ClassUtils.primitivesToWrappers() fails.





How to check if an Object instance is a valid return for a Method

I have an Object instance obj and a Method object method. How can I check to see if obj would be a valid return for the method?

Assume method has no parameters and it's not a return type of void (confirmed as a getter).

For example, if obj is null then the return type for method cannot be a primitive. Alright, got that figured out. However, Class.isAssignableFrom does not take into account unboxing and boxing from primitives. For example int.class.isAssignableFrom(Integer.class) returns false, but that would be a valid return for the method.

An option I could take is use Class.cast but using exceptions for programming flow is rather nasty and generating exceptions is also costly. But it is something I am aware of.

I'm kind of stumped on exactly how to figure this all out elegantly. Help would be much appreciated.





dimanche 24 avril 2016

How JVM stores meta information of a class?

We use reflection for a user defined class Employee as:

Employee e = new Employee();
Class c = e.getClass();

As per my knowledge first JVM loads the bytecode of the class Employee, then it also create an object of Class.class for each loaded class (class Employee here). In the object of Class.class JVM stores meta information about the recently loaded class.

Meta information of a class are "name of methods", "name of fields" etc. Class of these types such as "Method", "Field" etc are defined in java.lang.reflect package.

I seen code of Class.java. I found methods in Class.class which are returning objects or array of objects of these types such as "Method", "Field" etc. But there is not a field in Class.class whose type is "Method", "Field" etc.

If my above statements are wrong, please make me correct. If above statements are not wrong then I have following doubts: 1). In which field of Class.class various information about a class get stored? 2). In which memory area of JVM object of Employee and object of Class.class get stored? 3). In which memory area of JVM bytecode of Employee and bytecode of Class.class get stored?





How to get the package name of an external .class (Java Reflection)

Here is my folder : /Users/huyvo/Desktop/demo It contains .class

How do I get the package name of an external .class?

public static Set<Class<?>> loadPackageFromPath(String path){
Set<Class<?>> thePackage = new HashSet<>();

FilenameFilter classFilter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".class");
    }
};

File f = new File(path);


if(f.isDirectory())

for (File file : f.listFiles(classFilter)){ 

    String packageName =  // Package name??


    String className =  packageName + "." + file.getName().substring(0, file.getName().lastIndexOf('.'));


    try { 
        thePackage.add(Class.forName(className));

    } catch (ClassNotFoundException e) { e.printStackTrace(); }  
}   

return thePackage;

}





What else do I need to check to determine if Class B uses Class A? (Java Reflection)

I have a function that aims to check if Class B uses Class A.

Local variables are not needed.

Currently I am checking for:

  1. If Class B extends A
  2. The arguments for the constructors of Class B
  3. If Class B methods return A
  4. The arguments of the methods of Class B
  5. The field types of Class B

This problem is like the halting problem. I am I miss anything else?





How to get method parameter classes using Reflection?

For example, if I'm reading through a class C that has a method public void (Foo f) and I'm using reflection, how do I check the method parameter and get the name of the class / object type (Foo)? I tried calling getDeclaredMethods(), then for every method in that array, getParameterTypes(), but that doesn't work. It also gives me a NullPointerException. It lets me do this for fields (e.g. field.getType() and then returns a class) so how can I do that with methods?

 Method[] methods = current.getDeclaredMethods();
            for(Method m: methods){
                numMethods++; //increment # total methods
                Class[] params = m.getParameterTypes();
                if(params.length>0){
                    for(int x = 0; x < params.length; x++){
                        int col = Arrays.asList(classArray).indexOf(params[x]);
                        theData[i][col] = 1;
                    }
                }
                //System.out.println("Current class: " + current.getName());
                //System.out.print(m.toString()+ "\n");
            }

Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at DesignerAnalyzer.createData(DesignerAnalyzer.java:155)
    at DesignerAnalyzer.loadPackage(DesignerAnalyzer.java:122)
    at DesignerAnalyzer.main(DesignerAnalyzer.java:198)
Java Result: 1





Is it bad practice to use Object.getClass() in Java?

I am well aware of the fact that reflection should only be used as a last resort, and even if you are in a situation where it seems you should rely on it may imply bad design on your part. It's a very powerful tool that should only be used with extreme caution.

I am also aware that Java stores some housekeeping information about objects, so in theory it should be a relatively cheap operation to determine the dynamic type of an object with Object.getClass() (at least cheap compared to languages without such housekeeping data, for example C++, where expensive vtable lookups are needed for RTTI).

Is this really the case? Is it considered bad practice in Java to check if an object of some base is a certain derived type using getClass()?





Find which methods an object is used in using reflection

Given a single assembly, is there a way to find out how many times and from where a particular class is called? Example:

// CustomDbContext: Entity Framework DbContext
var type = typeof(CustomDbContext);

var types = typeof(CustomDbContext)
    .Assembly
    .GetTypes()
    .Where(t => t != typeof(CustomDbContext))
    .ToList();

foreach (var type in types)
{
    var methodInfos = type
        .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
        .ToList();

    foreach (var methodInfo in methodInfos)
    {
        var methodBody = methodInfo.GetMethodBody();

        // Is it possible to determine whether the [CustomDbContext] class has been instantiated or referred to?
    }
}

I know this is possible when analyzing code (say using Roslyn), but I'm interested in finding out if we can get this info from a compiled assembly.





samedi 23 avril 2016

Is there a way to pass a method as a parameter to a method?

I'm writing a program and I want to know if I can pass a method as a parameter of another method. For example, something of the following:

public boolean update(Method m){ //input is a method
    int i = m.execute();
    // logic relating to the value of i
}

I want to know if I can do this in java. I'm currently reading about functional programming and Reflection right now.





Getting a reference to a Kotlin function as a Java Method

I have a Java method that takes a Method parameter:

void doSomethingWithMethod(Method m) {
    ...
}

And I have a Kotlin class that contains a function:

class MyClass {

    fun myFunction() : List<Something> {
        ...
    }

}

I can get a reference to the function with MyClass::myFunction, but I don't see a way to pass it into the doSomethingWithMethod method. Is there an equivalent to the .java property that can be applied to a Kotlin class reference to get its Java equivalent?

If not, is there a workaround?





Java: Is it possible to add a proxy to a live object instance during runtime?

I know Java supports proxies. I've been checking Javassist but not sure whether it can support the following trick:

public class Hello {

    public void hi() {
        System.out.println("hi");
    }
}

Hello hello = new Hello();

Hello proxyHello = createProxy(hello);
proxyHello.hi(); // method will be intercepted by a predefined proxy

Is it possible to do something like that?





Scala: Set a value based on parameter-type

I have a beginner question related to scala implicit:

class Box[T] {
  var value = Option(None)

  def pickValueUsingTypeOfT [T]: Unit = {
    val list = List("string", 1, new myClass(1D) )
    //value = Option ( find right element from the 'list' )
  }
}

class myClass(double: Double) {}


object Setter {

  def main(args: Array[String]) {
    val n: Box[String] = new Box[String]
    n.pickValueUsingTypeOfT
  }
}

The objective is to set the value according to type of T.





How come there's no 'this_class' - the static equivalent of 'this'?

When you're in a C++ non-static method, you can use the this variable to refer to the current instance; and through the instance you also have the type. In static methods, I would expect to have something like a this_class type available to me, which is the type of the class in which I'm implementing the method. Even if it's not inherited (i.e. for class B : public A, method A::foo() will have this_class being A even when accessed through B) - it would still be useful, for example when you're implementing a static method in a class with many template arguments, and you want to call some out-of-class function templated on your class's type.

So, was this possibility ever considered? Are there reasons it would complicate things for the developer or the compiler?





vendredi 22 avril 2016

How to compare same PropertyInfo with different ReflectedType values?

Here's a simple test demonstrating the problem:

class MyBase { public int Foo { get; set; } }    
class MyClass : MyBase { }    
[TestMethod]
public void TestPropertyCompare()
{
    var prop1 = typeof(MyBase).GetProperty("Foo");
    var prop2 = typeof(MyClass).GetProperty("Foo");
    Assert.IsTrue(prop1 == prop2); // fails
    //Assert.IsTrue(prop1.Equals(prop2)); // also fails
}

I need a comparing method which will determine that these two properties are equal. What is the correct way of doing this?

I see that there are few problems: overriden/hidden properties, interface properties. Is it so hard to compare properties?





Reflection Performance - Create Delegate (Properties C#) With Conditional Parameters

I am using the solution of the question: Reflection Performance - Create Delegate (Properties C#)

Where I have the following code:

private static Action<object, object> BuildSetAccessor(string name, MethodInfo method)
{
    if (method == null) return null;
    if (method.DeclaringType == null) return null;
    var obj = Expression.Parameter(typeof(object), name);
    var value = Expression.Parameter(typeof(object));
    var expr = Expression.Lambda<Action<object, object>>(Expression.Call(Expression.Convert(obj, method.DeclaringType), method, Expression.Convert(value, method.GetParameters()[0].ParameterType)), obj, value);
    return expr.Compile();
}

private static Func<object, object> BuildGetAccessor(string name, MethodInfo method)
{
    if (method.DeclaringType == null) return null;
    var obj = Expression.Parameter(typeof(object), name);
    var expr = Expression.Lambda<Func<object, object>>(Expression.Convert(Expression.Call(Expression.Convert(obj, method.DeclaringType), method), typeof(object)), obj);
    return expr.Compile();
}

Code in use...

var cacheProperty = new CacheForReflectionClassProperty()
                {
                    Name = p.Name,
                    SetValue = BuildSetAccessor(p.Name, p.GetSetMethod()),
                    GetValue = BuildGetAccessor(p.Name, p.GetGetMethod())
                };
if (Attribute.IsDefined(p, typeof(IsIdentityColumn)))
{
    // TODO: Instead of just getting the old value, 
    // I need to verify if the value is NULL
    // in that case I need to create a new value of ID type....
    // and at the end I need to use the SetValue() method as well
    GetValue = .... // TODO: 
}
else if (Attribute.IsDefined(p, typeof(IsCreatedOnColumn)))
                {
    // TODO: Instead of just getting the old value, 
    // I need to verify if the value is NULL
    // in that case I need to create a new value with DateTime.UtcNow
    // and at the end I need to use the SetValue() method as well
    GetValue = .... // TODO:
                }

I know that I will need to create the following methods:

private static Func<object, object> BuildGetAccessorForIdentityColumn(string name, MethodInfo method)

private static Func<object, object> BuildGetAccessorForCreatedOnColumn(string name, MethodInfo method)

I have tried to learn on how to use Expression trees but I have not found a way where my BuildGetAccessor is not only getting the value but also comparing the result with something and if needed also needs to use the BuildSetAccessor.

How can I do this?





How to determine if type member is an enum?

I figured out that I can use GetMembers() to return the members of the class, but I would like to return only the enum members. While debugging I can hover over member and see an IsEnum property that is true, but I can't seem to get to it in code.

I would like for only IAmAnEnum to be printed in the following code. Currently the code will print both IAmAnEnum as well as IAmAClass.

static void Main(string[] args)
{
    foreach (var member in typeof(Test).GetMembers())
    {
        //if (member.IsEnum) // <-- Compile error
        //{
        Console.WriteLine(member.Name);
        //}
    }

    Console.Read();
}

public class Test
{
    public enum IAmAnEnum
    {

    }

    public class IAmAClass
    {

    }
}





What is System.Reflection.RuntimePropertyInfo and how do I compare it?

I was suprised to see that the actual type of the object I get with x.GetType().GetProperty("Foo") is not System.Reflection.PropertyInfo but System.Reflection.RuntimePropertyInfo.

I don't see this type documentation in msdn or elsewhere.

My actual problem grows from reference-comparing two properties. I receive a property from third-party lib and compare it with a property which I get with .GetProperty("Foo") on the same type. I expected properties to be the same object (and they looks like the same property in "Locals" window while debugging), but they are not (GetHashCode result is different). So, I think it can somehow be related with the actual type of the property object which is System.Reflection.RuntimePropertyInfo.

What is System.Reflection.RuntimePropertyInfo? How to compare it? Does it behaves the same as usual PropertyInfo?





GetAll private member ZendFramework

Is there a way to list all private member of an instance with ZendReflection?

The documentation is very light http://ift.tt/1VLXRGy I can't get any way to do that.





Where can I find the specification for the Class.getProtectionDomain().getCodeSource() method?

Regardless of whether I use the Oracle JDK, IBM JDK or the Open JDK (all version 8), I'm noticing that the following method is always returning null when the class in question is a JDK library class:

    Class clazz = Integer.class;
    CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); 

What I would like to know is whether or not the fact that this is null for a set of classes (namely, the classes supplied by the JDK) is specified somewhere (as opposed to it being a commonly-agreed upon value for these classes, decided by the various implementers).

However, I can't seem to find where this would be specified. I've already checked the following sources and have not found any mention there:

  • The Java SE 8 JLS
  • The Java SE 8 JVM Spec
  • JSR-115 (JavaTM Authorization Contract for Containers 1.5)

Where is this behaviour specified? Or is it indeed not specified and a "happy coincidence" that all three JVM implementations have the same behaviour?

(Bonus points if you can explain how this is implicitly specified as a result of other specifications, which I suspect to be the case!)





Python patch object method

I want to simulate ping timeout of a websocket in a test.

First I tried to close TCP socket quietly but it's not possible due FIN is sent anyway. iptables is not an option.

I use tornado library to mock a websocket client.

I read how to replace method in already instantiated object. It works in a simple demo, but tornado seems to ignore my manipulations.

What it could be?

import types

ws.websocket_connect(url, callback=openCallback,
            on_message_callback=messageCallback)

def openCallback(future):
    ws = future.result()
    inst = ws.protocol

    def stub(self, x):
        print "STUB"
    inst.write_ping = types.MethodType(stub, inst, inst.__class__)

There is no any error, but stub is not called and client still replies for server ping requests.





Get derived class via reflection? [duplicate]

This question already has an answer here:

I have 2 dlls, one with an interface and another that actually uses the interface. I can call the 2nd dll using reflection, but I wanted to know if I can get more information about it using the interface.

I have something like...

// the interface dll
namespace Mynamespace{
  public interface Interface1
  {
    int Add( int a, int b);
  }
}

and another interface in the same dll...
note that it is derived from the first one.

namespace Mynamespace{
  public interface Interface2 : Interface1
  {
    int Sub( int a, int b);
  }
}

I then call a method using reflection

// get the 2 interfaces
var asm = Assembly.LoadFile( dllInterfacePath);
var type1 = asm.GetType("Mynamespace.Interface1");
var type2 = asm.GetType("Mynamespace.Interface2");

// get the main class
var asmDll = Assembly.LoadFile( dllPath);
var type = asmDll.GetType("MyMS.SomeClass");

// create an instance
var instance = Activator.CreateInstance( type, null );

Now my question is how can I tell if the instance created is derived off Interface2 or Interface1, I could look for method "Sub(...)" and if it is not present then I know it is of type Interface1.

But I was wondering if there was a better function to dynamically achieve this?





jeudi 21 avril 2016

How would I use Java reflection in this case?

I am working on a Maven project that includes a few object classes. My code centers around controlling start times and end times for a particular functionality in three different environments that are separate in IntrAnet and IntErnet domains. So my object structure looks something like:

IntrAnet:
  env1:
    startTime:
    endTime:
  env2:
    startTime:
    endTime
IntErnet:
  env1:
    startTime:
    endTime:
...

Now, in my controller class, I want to use the start time and end time depending on what environment and domain the user is in. So I have code that looks like:

if(domain == "IntrAnet") {
   if(env == "env1") {
     String startTime = overallClassVO.env1IntrAVO.getStartTime();
     String endTime = overallClassVO.env1IntrAVO.getEndTime();
     ...
   }
   if(env == "env2") {
     String startTime = overallClassVO.env2IntrAVO.getStartTime();
     String endTime = overallClassVO.env2IntrAVO.getEndTime();
     ...
   }
}
if(domain == "IntErnet") {
   if(env == "env1") {
     String startTime = overallClassVO.env1IntErVO.getStartTime();
     String endTime = overallClassVO.env1IntErVO.getEndTime();
     ...
   }
   if(env == "env2") {
     String startTime = overallClassVO.env2IntErVO.getStartTime();
     String endTime = overallClassVO.env2IntErO.getEndTime();
     ...
   }
}

My code is a little more complex, but that is the general idea. I know reflection is useful in simplifying repetitive code by calling classes based on the object during runtime, but I am wondering if I can use reflection in this case.





How to understand "{}" sign in below code?

Type type = new TypeToken<List<String>>() {}.getType();

Please tell me the code above in "{}" What does it mean?





How to make this boolean statement false through Java Reflection

I have to use reflection.

In my ATM class I have two variables:

   private int userBalance = 100;
   private int moneyInMachine = 100000;

I would like to withdraw an unlimited amount of money.

Here is the ATM's withdraw function:

private void widthdrawAmount(int n) {
    if (this.userBalance - n < 0 || this.moneyInMachine - n < 0) {
       // You can not pull money out.
    }

    this.updateScreen();
}

I was wondering if anyone knows a way to take this boolea statement false.





mercredi 20 avril 2016

How to call MouseEvent using Reflection

This is the piece of code I would like to call with Java reflection:

private void cardSlotMouseClicked(MouseEvent mouseEvent) {
  // Some stuff

 }

Here is the code in the class ATM that calls it:

  // cardSlot is a JPanel

  this.cardSlot.addMouseListener(new MouseAdapter(){

        @Override
        public void mouseClicked(MouseEvent mouseEvent) {
            ATM.this.cardSlotMouseClicked(mouseEvent);
        }
    });

Here is my code:

    Class a = ATM.class;

    Method m = a.getDeclaredMethod("cardSlotMouseClicked", MouseEvent.class);


    m.setAccessible(true);

    Object o = a.newInstance();

    m.invoke(o, "?"); // What is the argument?

I tried MouseEvent.BUTTON1 but it does not work.





Create properties dynamically

So I have an object with lots of properties, PropertyNameYear1, PropertyNameYear2, PropertyNameYear3...for 20 years. these properties could potentially grow with time, so in the future I might have to add PropertyNameYear21 and so on.

I'm trying to get these properties, both their name and value, without specifying each and every one, since theoretically i can have tens of them. I can do it using LINQ and Object Initializer, but then I have to specify each property twice:

new {
    PropertyNameYear1 = f => f.PropertyNameYear1,
    PropertyNameYear2 = f => f.PropertyNameYear2,
    ...
};

How can I, using LINQ (and Refelction?), get all these properties (and only these, assuming there are other properties named differently than PropertyNameYearX) into a new/another object and return that object?

This is a pseudo-code of what I'm looking for:

public ReturnType GetSomeObjectWithSpecificProperties(int ID){
    var list = SomeObjectRepository.Where(f => f.ID == ID);
    var props = list.GetType().GetProperties().ToList();
    var SomePropObjectList = props.Where(f => f.Name.Contains("PropertyNameYear")).ToList();

    var listToReturn = SomePropObjectList.Select(f => new {
        f.Name = f.GetValue(list)
    }).ToList();

    return listToReturn;
}





How do I get custom properties of a class with TypeDescriptor.GetProperties()

I'm trying to retrieve custom properties of a class that inherits ICustomTypeProvider, that have custom properties created during run time similar to what is described here: http://ift.tt/1Sc2TtD

If I use TypeDescriptor.GetProperties(myObject, false) only the properties defined at design time are returned. How do I retrieve any custom properties that object may have if it inherits from ICustomTypeProvider?





Invoke a COM Method using InvokeMember

I am wrapping a COM API Ultimately I am trying to push more code down into Generics and the inheritance pattern in the api is not helping.

I have a generic of IBase, THere are ~80 classes that represent result sets. They are very similar, but they all inherit, or rather implement, the very basic IBase.

I have tried Extension methods and I dont think that is the way to go because the com is late bound and using Reflection.PropertyInfo seemed to be a dead end.

In the generic, we have the sub types, so I think I can use InvokeMember to call the methods/properties I need.

instnc = Activator.CreateComInstanceFrom(assy, tyepname)
retClass = Type.GetTypeFromProgID(progId)

My challenge is that I can not find the progId. I have searched the registry, I have made many guesses. "Excel.Application" works, so the basic approach is solid.

THe com dll in question is the Intuit Quickbooks api. I have tried many variations of

"QBFC13Lib.ICustomerRetList"

Am I on the right track? If so, where can I find the progId? Should I try a different tack?





What is the best way to approximate class.getSimpleName() without loading class?

Given a fully qualified class name that can be loaded with Class.forName(), is there a way to transform the name into what would be the result of loading the class and invoking getSimpleName() without actually attempting to load the class? I need this capability for reflection purposes.





Mark class field

I am looking for a way to mark a field, and use that mark later for different operation on the object.

For example, serialize object without the marked fields:

class A(){
   public $field1;

   //@dont_serialize
   public $field2;
} 

$obj = new A();
$obj->field1 = "important data";
$obj->field2 = "not important data";

function MySerialize($obj){
  $arr = (array) $obj;
  $new_arr = array();   
  foreach ($arr as $key => $value) {
      if (THIS FEILD IS NOT MARKED AS @dont_serialize)
      {
        $new_arr[$key] = $value
      }
  }
  return serialize($new_arr);
}

How can I implement MySerialize() that will not serialize marked fields ?





Clone of Static Clas

I am using static list to keep some string values, when application starts just one static list is enough, but after a while i need to keep different strings in different static lists, is there any way to deep copy or clone of a static class with different name at the runtime in C#

public class Foo
{
    public static List<string> orders;
}

as you can see above, I can add and remove static Foo.orders easily, but in runtime i need another class for example Foo2 class. By the way, list must be static, however i need to reach list from different classes, also a cannot create new classes while developing, because how many static list I do not know

thank you





Reflection class to get all properties of any object not returning all properties

I have to find out all the properties within the object for that I am using method e.GetType().GetProperties()

e is dynamic type inheriting from IEvent . e has multiple propertie s

Issue which I am facing is propertyInfos collection does not contain ABC.Domain.Contract.Base.DInfo from RSummary and only it has ABC.Comon.Contract.Base.DInfo from REventBase Class

I need both the classes should come in propertyInfos collection.

Is there any specific property which I have to provide which will bring all DInfo irresppective of there namespaces

namespace MyNamespace
{
 public class Class1
    {

        {
        private static void ProcessEvents ()
            {
                try
                {
                    foreach (var e in allEvents)
                    {
                        try
                        {

                            PropertyInfo[] propertyInfos;

                            //MemberInfo[] info = type.FindMembers(MemberTypes.All, BindingFlags.Instance | BindingFlags.NonPublic, new MemberFilter(searchFilter), "tt");
                            //MemberInfo[] info = type.FindMembers(MemberTypes.All, BindingFlags.Default, new MemberFilter(searchFilter), "Submitted");
                            propertyInfos = e.GetType().GetProperties(
                                BindingFlags.Public | BindingFlags.NonPublic // Get public and non-public
                                | BindingFlags.Static | BindingFlags.Instance // Get instance + static
                                | BindingFlags.FlattenHierarchy | BindingFlags.ExactBinding);
                            foreach (var property in propertyInfos)
                            {
                                if (property.PropertyType ==
                                    typeof (ABC.Domain.Contract.Base.DInfo))
                                {
                                    //Do something 
                                }
                                else
                                {
                                    //Do something  Do Something Else
                                }
                            }
                        }


                    }
                }
            }
        }

        public class FSubmitted : RecordEventBase
        {
            public RSummary NewForm { get; set; }
        }

        public abstract class REventBase : Event
        {

            public Guid RId { get; set; }


            public  ABC.Comon.Contract.Base.DInfo RDInfo { get; set; }
        }

        public class RSummary
        {
            public Guid ID { get; set; }
            //public FormType Type { get; set; }

            public FRef FRef { get; set; }

            public ABC.Domain.Contract.Base.DInfo Submitted { get; set; }

            public ABC.Domain.Contract.Base.DInfo Saved { get; set; }

            public ABC.Domain.Contract.Base.DInfo Signed { get; set; }

            public bool IsSigned { get; set; }
        }

    }
}

namespace ABC.Domain.Contract.Base
{
    public class DInfo
    {
         public bool someThing { get; set; }
    }
}

namespace ABC.Comon.Contract.Base
{
    public class DInfo
    {
         public bool someThing { get; set; }
    }
}





get object size in bits with reflection in java

I want to get the size of the object I built with java.reflection. Here is the code. I don't understand what I'm doing wrong. When I get the object I'm tried to use instrument interface but it doesn't work. Thanks for helping !

public String analayzeData(Object obj) throws IllegalArgumentException, IllegalAccessException{
        Class c =  obj.getClass();
        System.out.println(sizer.getObjectSize(obj));
        String dataText="*************Start of " + c.getSimpleName() + " Class*************\n";
        Class superclass = c.getSuperclass();
        if(superclass!=null && !superclass.isAssignableFrom(Object.class)){
            Field[] superField = superclass.getDeclaredFields();
            for(Field field : superField){
                field.setAccessible(true);
                Object fieldVal = field.get(obj);
                dataText+=field.getName() + " = " + fieldVal + "\n";
            }
        }
    //  Instrumentation objectSizes =null;

        Field[] fieldType= c.getDeclaredFields();
        for(Field field : fieldType){
            field.setAccessible(true);
            dataText+=field.getName() + ":";
            Object fieldVal = field.get(obj);
            if(fieldVal instanceof ArrayList){
                ArrayList<?> arrayListField = (ArrayList<?>)fieldVal;
                dataText+="Size of " + field.getName() +" ArrayList = " + arrayListField.size() + "\n";
                for (int i=0; i < arrayListField.size();i++){
                    dataText+=analayzeData(arrayListField.get(i));
                }
                dataText+="****End of " + field.getName()  + "List****\n";
            }
            else
                dataText+= " = " + fieldVal+"\n";
        }
        dataText+="*************End of " + c.getSimpleName() + " Class*************\n";
        return dataText ;
    }

}
class sizer{
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }

}





How to check whether an object has certain method/property of particular type within it?

I have DInfo class present in two different namespaces i.e. ABC.Domain and ABC.Common I am getting xml body as a record from database from which I am deserializing to respective type. I have to find out all the records which are using properties with name/names of properties of type ABC.Domain.DInfo and just ignore of type ABC.Common.DInfo

As a I am getting record of type IEvent i.e may be FSubmitted or GSubmitted

namespace ABC.Domain
{
    public class DInfo
    {
        public DateTime? Date { get; set; }
        public URef User { get; set; }
        public Decimal? L1 { get; set; }
        public Decimal? L2 { get; set; }
    }
}
namespace ABC.Common
{
    public class DInfo
    {
        public DateTime? Date { get; set; }
        public URef User { get; set; }
        public Decimal? L1 { get; set; }
        public Decimal? L2 { get; set; }
    }
}

public class Event : IEvent
{

    public Guid Id { get; set; }

    public Event() { }

    public int Number { get; set; }
}

public interface IEvent : IRBase
{
    Guid Id { get; set; }

    int Number { get; set; }

}
public interface IRBase
{
    string RUser { get; set; }
    string Sub { get; set; }
}

public abstract class REventBase : Event
{
    public Guid Id { get; set; }
}


public class FSubmitted : REventBase
{
    public RSummary NewForm { get; set; }
}
public class GSubmitted : REventBase
{
    public FRef NewForm { get; set; }
}

public class RSummary
{
    public Guid ID { get; set; }

    public FRef FRef { get; set; }

    public ABC.Common.DInfo Submitted { get; set; }

    public ABC.Common.DInfo Saved { get; set; }

    public ABC.Domain.DInfo Signed { get; set; }
}


public class FRef : NIdentifier<Guid>
{
    public FormType Type { get; set; }
    public Version Version { get; set; }
    public ABC.Common.DInfo Submitted { get; set; }
    public ABC.Domain.DInfo Saved { get; set; }
}





mardi 19 avril 2016

How to convert IEnumerable

I am stuck with the following problem:

I normally use the function below to transfer custom data to DataTable but in this case the input data is a class composed of lists. I just need to write in DataTable the first element of each list per row. Could you help me to adjust this function in order to achieve this?

    public List<int> xID { get; set; }
    public List<string> xName { get; set; }
    public List<string> xType { get; set; }
    public List<string> xSource { get; set; }
    public List<int> xmdID { get; set; }
    public List<string> xMDName { get; set; }
    public List<string> xUser { get; set; }

    public static DataTable ListToDataTable<T>(IEnumerable<T> list)
    {
        Type type = typeof(T);
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        foreach (T entity in list)
        {
            object[] values = new object[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity);
            }

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }





C# Get value of Enum instance

Say I have this enum:

public enum MyEnum{
    ValueOne = 1,
    ValueTwo = 2,
    ValueThree = 3
}

And then this field/variable:

public MyEnum myEnumInstance = MyEnum.ValueTwo;

I need to the the name of myEnumInstance via reflection.

What I tried:

myClassInstance.GetType().GetField("myEnumInstance").GetValue(myClassInstance)

Which always returns ValueOne, no matter what myEnumInstance is set to.

How can I get the string value/name of the enum field via reflection?