lundi 31 juillet 2017

C# - Get Description Attributes From a Flagged Enum

I am trying to create an extension method that will return a List<string> containing all the Description attributes for only the set values of a given [Flags] Enum.

For example, suppose I have the following enum declared in my C# code:

[Flags]
public enum Result
{
    [Description("Value 1 with spaces")]
    Value1 = 1,
    [Description("Value 2 with spaces")]
    Value2 = 2,
    [Description("Value 3 with spaces")]
    Value3 = 4,
    [Description("Value 4 with spaces")]
    Value4 = 8
}

And then have a variable set as:

Result y = Result.Value1 | Result.Value2 | Result.Value4;

So, the call I want to create would be:

List<string> descriptions = y.GetDescriptions();

and the final result would be:

descriptions = { "Value 1 with spaces", "Value 2 with spaces", "Value 4 with spaces" };

I have created an extension method for getting the single description attribute for an Enum that can not have multiple flags set that is along the following lines:

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        System.Reflection.FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr =
                   Attribute.GetCustomAttribute(field,
                     typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null;
}

And I've found some answers online on how to get ALL the Description attributes for a given Enum type (such as here), but I'm having problems writing a generic extension method to return the list of descriptions for only the set attributes.

Any help would be really appreciated.

THANKS!!





Can guava be used for reflection on classes that are loaded by name?

In this question I was referred to guava as a solution for reflection on generics, and it looks awesome except that I get errors trying to use this on classes loaded by name:

Class clazz = Class.forName("net.redpoint.scratch.Derived");
TypeToken tt = new TypeToken(clazz) {};

This results in the error: java.lang.IllegalArgumentException: class com.google.common.reflect.TypeToken isn't parameterized

Is there some way to use TypeToken without having the class at compile-time? Note that I also do not have source to these classes.





Get contained type of list in generics, lambda

Even though I know that such libraries already exist, I have decided to create an MVC5 HtmlHelper library to generate Tables from a model. The point is to practice (actually learn) about generics and lambdas in C#.

I want my library to be able to generate an HTML table using a syntax such as:

@Html.DisplayTable(model => model.ListTest).Render()

At this point in time, the above code works perfectly. But when I attempted to add the method exclude it all went wrong ... And this is where I see how poor my understanding of lambdas and delegate is. (it is actually the first I wrote any code that took a delegate as a parameter)

Below is how I want my call to be made

@Html.DisplayTable(model => model.ListTest).Exclude(l => l.Col1).Render()

then here is the model that I provide to my view

public class TestViewModel
{
    public List<RowViewModel> ListTest { get; set; }
}

where RowViewModel is defined as follow

public class RowViewModel
{
    public string Col1 { get; set; } = "Col1Value";
    public string Col2 { get; set; } = "Col2Value";
    public string Col3 { get; set; } = "Col3Value";
}

My helper

public static class TableHelpers
{
    public static HtmlTable<TValue> DisplayTable<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression) where TValue : IList
    {
        Func<TModel, TValue> deleg = expression.Compile();
        var result = deleg(helper.ViewData.Model);

        return new HtmlTable<TValue>(result);
    }
}

And my "library logic"

 public class HtmlTable<TValue> where TValue : IList
{
    private TValue _inputModel;
    private readonly TableViewModel _outputViewModel = new TableViewModel();

    public HtmlTable(TValue model)
    {
        Init(model);
    }

    public HtmlTable<TValue> Init(TValue model)
    {
        if(model.Count == 0)
            throw new ArgumentException("The list must not be empty");

        _inputModel = model;

        UpdateViewModel();

        return this;
    }

    private void UpdateViewModel()
    {
        var subType = _inputModel.GetContainedType();

        var properties = subType.GetProperties();
        _outputViewModel.Header = properties.Select(p => p.Name).ToList();
        _outputViewModel.Rows = new List<List<string>>();
        foreach (var row in _inputModel)
        {
            var values = _outputViewModel.Header.Select(col => subType.GetProperty(col).GetValue(row, null).ToString()).ToList();
            _outputViewModel.Rows.Add(values);
        }
    }

    public HtmlTable<TValue> Exclude<TSubValue>(Expression<Func<TValue, TSubValue>> expression)
    {

        Func<TValue, TSubValue> deleg = expression.Compile();
        var result = deleg(_inputModel);

        return this;
    }
}

I kind of have an idea of how it should be done if i was to specify the model of a row to my helper such as

@Html.DisplayTable<RowViewModel>(model => model.ListTest).Exclude(l => l.Col1).Render()

but I would really like to be able to determine the type contained in a list to make lambdas work.

All of this might not make any sense, but after struggling with understand lambdas from a theory point of view for a while i decided that it was better to stop reading articles and try to do something with it ...





Java reflection: getting correct type of parameterized generic superclass method

I am using reflection to discover methods of classes and their superclasses, along with the types of method arguments and return values. This mostly works, but I'm having trouble with some specific generic cases. Suppose I have a base class:

package net.redpoint.scratch;
public class Base<E> {
    public E getE() { return null; }
}

And a subclass:

package net.redpoint.scratch;
public class Derived extends Base<String> {}

Using reflection I can walk through the methods of Derived and get arg and return types (code omitted, but it works fine). However, I also want to know the inherited methods. Using code below, I can come very, very close. But getting the correct return type of getE() eludes me. I can get the generic type "E" but not the actual type "java.lang.String":

package net.redpoint.scratch;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
public class Scratch {
  public static void main(String[] args) throws Exception {
    Class clazz = Class.forName("net.redpoint.scratch.Derived");
    Type superType = clazz.getGenericSuperclass();
    if (superType instanceof ParameterizedType) {
      ParameterizedType superPt = (ParameterizedType)superType;
      Type[] typeArgs = superPt.getActualTypeArguments();
      Type t0 = typeArgs[0];
      // This is "java.lang.String"
      System.out.println(t0.getTypeName());
      Type superRawType = superPt.getRawType();
      if (superRawType instanceof Class) {
        Class superRawClazz = (Class)superRawType;
        for (Method method : superRawClazz.getDeclaredMethods()) {
          if (method.getName().equals("getE")) {
            Type returnType = method.getGenericReturnType();
            if (returnType instanceof TypeVariable) {
              TypeVariable tv = (TypeVariable)returnType;
              // This is "E"
              System.out.println(tv.getName());
              // How do I associate this "E" back to the correct type "java.lang.String"
            }
          }
        }
      }
    }
  }
}

The output is:

java.lang.String
E

My question is, how do I find that "E" is actually "java.lang.String"? I suspect it has something to do with a lookup into the typeArgs[], but I don't see how to get there. PLEASE do not respond unless you've actually worked with generics reflection. I've seen a lot of posts with answers like "type erasure prevents this", which is not true.





Get name of private property via reflection without using a string

i want to get the name of a private property of a class. Reason is i want to set a property of that class that will be obfuscated later. What i have so far is the following:

public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
    var lambda = expression as LambdaExpression;
    MemberExpression memberExpression;
    var unaryExpression = lambda.Body as UnaryExpression;
    if (unaryExpression != null)
        memberExpression = unaryExpression.Operand as MemberExpression;
    else
        memberExpression = lambda.Body as MemberExpression;

    if (memberExpression == null)
        throw new ArgumentException("Expression must point to a Property");

    return memberExpression.Member.Name;
}

being called like this

private static readonly string DisplayNameProperty = ReflectionUtil.GetPropertyName<MyClass>(x => x.MyPublicProperty);

The previous example showed usage of the Util with a public property and it works perfectly. But on a private property it won't work because its private obviously.

Now what will work is:

typeof(MyClass).GetProperty("MyPrivateProperty", BindingFlags.NonPublic | BindingFlags.Instance)
                .SetValue(_myInstance, true, null);

But after being obfuscated the property will not be called MyPrivateProperty anymore.

I hope you get my point.

Thanks for any help.





dimanche 30 juillet 2017

Is it possible to create an instance of parameterized class in Java?

I have the same logic in classes creation, but actual classes are different. Is it possible somehow to create an instance of a parameterized class?

Here is an example:

public class MyClass <E extends MyEntityClass> {
    public List<E> myList = new LinkedList<>();

    public MyClass(JsonArray params) {
        for(JsonElement param : params){
            myList.add(new E(param));
        }
    }
}

MyEntityClass - is the super class which has the constructor which accepts JsonElement.

I know that Java doesn't allow to create the parameterized class, but is it possible to solve somehow this problem?





SQLAlchemy doesn't map reflected class

I have this code:

def advertiser_table(engine):
    return Table('advertiser', metadata, autoload=True, autoload_with=engine)

And later I try this:

advertisers = advertiser_table(engine)
...
session.bulk_insert_mappings(
        advertisers.name,
        missing_advetisers.to_dict('records'),
    )

where missing_adverisers is a Pandas DataFrame (but it's not important for this question).

The error this gives me is:

sqlalchemy.orm.exc.UnmappedClassError: Class ''advertiser'' is not mapped

From reading the documentation I could scramble enough to ask the question, but not much more than that... What is Mapper and why is it so detrimental to the functioning of this library?.. Why isn't "the class" mapped? Obviously, what am I to do to "map" it to whatever this library wants it to map?





samedi 29 juillet 2017

ParameterInfo.DefaultValue returns null for value type

I have the following method signature:

static void SetControlSprite(string ctrlName, Sprite spr, Color color = default(Color))

Color is a standard simple RGBA struct type, that is roughly this:

public struct Color
{
    public float r;
    public float g;
    public float b;
    public float a;
}

When using reflection get the last ParameterInfo, for color, I get the following results:

parameterInfo.HasDefaultValue == true

parameterInfo.Defaultvalue == null

I was expecting DefaultValue to be a Color object with all values at zero. I don't see anywhere in MSDN a mention of value type parameters returning null default values.

The workaround is simple, but I'm surprised that I need it:

var defaultValue = parameterInfo.DefaultValue;

if (defaultValue == null && parameterInfo.ParameterType.IsValueType)
{
    defaultValue = Activator.CreateInstance(parameterInfo.ParameterType);
}

Is this normal? Is it documented anywhere?





Reflection: How to get the value of a field without evaluation?

Playing with java.lang.reflect and was wondering if there is any possibilities to get the assignment value of a java.lang.reflect.Field

Example

public class Dummy {
    String envHttpPort = System.getenv("HTTP_PORT");
}

From java reflection I would like the have the value System.getenv("HTTP_PORT"); returned instead of null as it seems by instantiation of the class, which as far as I know is required to retrieve the values of the Field would be the value of the System.getenv(String) call, which is not what I want.

Is it possible to read the field and value as is?

Wanted output would be the same as the source code.

I hope you guys understand if not please let me know and I will try and rephrase the question.





Reflection. How come java's static type system can allow you not knowing an object type at compile time?

I'm trying to find some useful cases for reflection on my own and i've just discovered an interesting thought from this post: it says,

say you have an object of an unknown type in Java

Can you provide a couple of examples of that with a plain English explanation?





vendredi 28 juillet 2017

Dynamically populate generic list of objects without concrete data type

I have a database with around 100 or so table. What I am trying to do is the following:

  1. Get a list of tables in the database.
  2. Loop through each table in the list, and select all records in the table into a Data Table.
  3. For each Data Table, dynamically generate a Generic List of POCO classes
  4. Read each Data Row and populate the object, then add it to the list.

I am getting through items 1 and 2 fine. But for items 3 and 4 I am having trouble. Here is the code I have:

Type type = Type.GetType(tableName);
var list = Utility.BindList<type>(dataTable);

The exception I get is: "'type' is a variable but is used like a type."

And thinking about it, it makes sense. Of course, if I enter the actual class instead of type it works fine:

Type type = Type.GetType(tableName);
var list = Utility.BindList<Person>(dataTable);

But I don't want to have to hard code any actual classes. By the way, here is the signature of the BindList method I am calling above (this part is working fine):

public static List<T> BindList<T>(DataTable dt)
{
    // Turn Data Table into Generic List

    return list
}

Does anyone have any suggestions on how to do this?

Thanks!





Cannot set certain type values via IL Emit on Object

I'm creating a function using ILGenerator and Emit to set the value of a property on a specified instance. The main reasons for this being the performance aspects to the solution I'm working on. I have a basic form of code which should take 2 objects and load them via IL to invoke a set function. The problem I am finding is the value I'm passing to be set seems to be ignored and another seemingly generated value is set in its place.

This is the basic usage example made in LinqPad I have created to demonstrate this problem:

void Main()
{
    var instance = new TestClass
    {
        Id = new Guid("f0564ce7-f249-4105-8fc4-2c65cfe095f6"),
        StringValue = "Something",
        IntValue = 0
    };

    MethodOne(instance);
}

private void MethodOne(TestClass instance)
{
    var setStringMethod = GenerateMethodAssignment("StringValue");
    setStringMethod(instance, "Something Else");

    var setGuidMethod = GenerateMethodAssignment("Id");
    setGuidMethod(instance, new Guid("f8b0fae2-40bb-422a-815f-2300cceb4329"));

    var setIntMethod = GenerateMethodAssignment("IntValue");
    setIntMethod(instance, 100);
    instance.Dump();
}

// Define other methods and classes here
public class TestClass
{
    public Guid Id { get; set; }
    public string StringValue { get; set; }
    public int IntValue { get; set; }
}

private Action<object, object> GenerateMethodAssignment(string propName)
{
    var setMethod = typeof(TestClass).GetProperty(propName).GetSetMethod();
    var argTypes = new Type[] { typeof(object), typeof(object) };
    var method = new DynamicMethod(Guid.NewGuid().ToString(), null, argTypes, GetType(), true);

    var ilGenerator = method.GetILGenerator();
    ilGenerator.Emit(OpCodes.Ldarg_0);
    ilGenerator.Emit(OpCodes.Ldarg_1);
    ilGenerator.Emit(OpCodes.Call, setMethod);
    ilGenerator.Emit(OpCodes.Ret);

    var action = (Action<object, object>)method.CreateDelegate(typeof(Action<object, object>));
    return action;
}

Output: Value set on object

The string value is set fine but a Guid or Integer value is not set as I would expect. I am fairly new to IL and may be having too high expectations here for the code to be this simple.

However even so I noticed running this code multiple times seems to generate the values for IntValue and Id in a seemingly sequential order so I curious where exactly these values are coming from.





Cannot reach properties of a reflected object from the jsf view

I'm trying to build a module for managing my database's catalogues like: country, enterprises, users etc. The user is supposed to select the catalog from a combobox and the system is supposed to display a table with the principal columns (not null in the database and some predefined by me). From the 3 objectives I have only achieved 2: 1.- get the @NotNull fields from the Entity Classes after selecting the catalogue using reflection 2.-display the table with dynamic columns retrieving them from the above also. But number 3 is giving me trouble. The thing is, I used this folling code in the view for displaying columns dynamically (based on the @NotNull fields I stored in an object) ,(http://ift.tt/2h8waeG):

<p:dataTable  id="conceptos" var="pojo" value="#{catalogoMB.comocombo}>
<p:columns value="#{catalogoMB.columns}" var="column" 
columnIndexVar="colIndex" sortBy="#{pojo[column.property]}" filterBy="#
{pojo[column.property]}">
        <f:facet name="header">
        <h:outputText value="#{column.header}" />
        </f:facet>
        <h:outputText value="#{pojo[column.property]}" />
</p:columns>
</p:dataTable> 

So for example, in a normal way, without reflection the code above will work like this: comocombo will have this properties: name, value, id; and my array of columns will be the same: name, value, id... The thing is, comocombo is a List<Object> object where I store field's reflection class values, which returns java.lang.class instead of the instance of the EntityClass although I managed to invoke setter and getter from an Object instance of that class (combito) -supposedly- so when I try to display pojo[column.property]-> comocombo["id"], comocombo["name"] or comocombo["value"] it sends me an exception saying that java.lang.class doesn't have this any properties....How can I reach them? I've read about Map<String, String> and of .cast() But I'm not sure this could be the way.

public void populateT(){ 
comocombo=new ArrayList<>();
Object tt ;
y = tabla.get(tabla.size()-1).getConcpetos(); //result of query type: 
FindAll from the entity Class 
try{
Class combito= Class.forName("sipe.services."+ catName); //the "path" of the 
Entity Classes
for (Integer j=0; j<y.size()-1; j++){
tt=y.get(j);
            for (Integer i=0; i< tabla.size()-1; i++){
            tucampo=minustomayus(y.get(j).getClass().getDeclaredField(tabla.get(i).getNombre_c()).getName()); //tabla.get(i).getNombre_c()-> here I've stored the @NotNull properties' names (countryid, countryname...) whic are the same in  columns = new ArrayList<ColumnModel>();  (catalogoMB.columns in the view) 
            Class cls= Class.forName("sipe.services."+ catName);
            Method method = cls.getDeclaredMethod("get"+tucampo); // for example "countryid" -> getCountryid              
            Class<?> type = null;
            for (Method methods : combito.getDeclaredMethods())
            { //Here I'm trying to invoke setter of the Entity Class in order to store its values..
              //equivalent to: if o is an instance of Entity Class Country: Country o = new Country(); o.setCountryid(2);
                if (methods.getName().contains("set"+tucampo)){
                type=method.getReturnType();
                methods.invoke(combito.newInstance(),method.invoke(tt));
             }
            }





How to relate a property to its backing field C#

I have a property that has its own private member backing field. I want to be able to relate the name of the property with the name of the backing field.

public bool AddPostDateToReference
{
    get
    {
        if (moAddPostDateToReference.Value.ToUpper() == "Y" || moAddPostDateToReference.Value.ToUpper() == "T") { return true; }
        else { return false; }
    }
    set
    {
        if (value) { moAddPostDateToReference.Value = "Y"; }
        else { moAddPostDateToReference.Value = "N"; }
    }
}

When doing a Quick-watch in the Visual Studio debugger, I am able to view the property "AddPostDateToReference" and the private member variable "moAddPostDateToReference" but not the relation on how they are connected.





How to go from a discriminated union representation of a type to a System type?

In F#, if I want to create a System.Type of say, an array of strings, I could just write typeof<string[]> and be done with it. That is because I can specify the type in the typeof at compile time.

type Ty =
| Int32
| Float32
| String
| Array of Ty

let to_dotnet_type: Ty -> System.Type = ...

But suppose I had an union type so that the exact System.Type I am looking for is unknown at compile time, how would I go from Ty to the .NET System.Type? Arrays in particular do not even have any generic parameters so I am guessing that F# is instantiating new array types that inherit from the base System.Array on demand. I am drawing a blank on how to do it dynamically.

The reason why being able to move between my internal representation and the CLR types would be beneficial is because I am making a language that compiles to F# (in F#) and am using reflection functions such as GetMethod which take arrays of System.Types as an argument. I am using them to do interop for lack of knowledge of any better ways of doing it.





Access level aware dependency injection into inherited field

At work there is a process framework. It uses keys and containers to set parameters without the use of dedicated constructors (it's basically the type safe heterogeneous container pattern).

I recently added dependency injection. Below you find an example (it lacks some null checks, access control, etc.)

  private static void inject(Process instance, Container c) throws Exception
  {
    Class<?> reference = instance.getClass();
    for (Field field : reference.getDeclaredFields())
    {
      Inject inject = field.getAnnotation(Inject.class);

      Key<Object> key = new Key<>(inject.key());
      field.set(instance, c.getObject(key));
    }
  }

The implementation is working, but know I need to enhance it in order to also inject into inherited fields.

I had no problem retrieving the type hierachy and all the annotated, inherited fields. But in order to comply with Java, I must not inject into every retrieved field.

Only when the field is:

  1. public
  2. protected
  3. package-privated and declared in a class that has the same package as reference
  4. private and declared in a non-static class that is enclosed by reference

Items 1 - 3 are easy to check for. I have difficulties with the last item. Is there an elegant solution?

I thougt about using java.lang.Class.isMemberClass() and comparing class names.

Currently my check looks like this

  private static boolean accessAllowed(Class<?> reference, Field field)
  {
    int modifiers = field.getModifiers();

    boolean hasAccess = Modifier.isPublic(modifiers);
    hasAccess |= Modifier.isProtected(modifiers);

    // TODO fix
    hasAccess |= Modifier.isPrivate(modifiers) /* add check */;

    // no access and not private means field is package-private
    if (!hasAccess && !Modifier.isPrivate(modifiers))
      hasAccess = reference.getPackage().equals(field.getDeclaringClass().getPackage());

    return hasAccess;
  }

Is there an easy and/or efficient way to find out whether a class is enclosed by another class? Or is there another way to find out whether I am allowed to inject?





Android Java Reflection plus Internationalization

I don't know if it is possible to accomplish this but I'd like to discuss the matter anyways. I have a very long profile screen with aprox. 25 rows:

enter image description here

I want to create this screen programmaticaly with ListView and Adapter. I managed to do it using reflection so I could use the attribute name to the left as the field label, but that's not enough - as you can see, the app is currently in pt-BR but I also need it in en-US.

This is my class:

public class UserGeneralData {
@SerializedName("login")
private String login;

@SerializedName("name")
private String name;

@SerializedName("surname")
private String surname;

@SerializedName("mail")
private String mail;

@SerializedName("dateOfBirthday")
private String birthday;

@SerializedName("docCpf")
private String cpf;

@SerializedName("docRg")
private String identity;

@SerializedName("military")
private boolean military;
...

So, how can I change the language if I'm not using strings from the xml file?





Jackson Pojo to correct Implementation

I am in a situation where I can't wrap my head around the solution. The Problem is that I can't use CDI.

Let me show you my sorrounding. I am developing a java console application to later on perform long time tests and simulations. These are needed to find bugs and behaviour of our real application for some tasks and scenarios running over weeks etc.

I have this POJO structure:

POJO structure

And I am using Jackson to import settings for the various number of implementations I receive. The JSON looks like this for my POJO Wrapper:

{
    "devices": [
    {
    "host": "asd",
    "port": 136,
    "protocol": "rollenschneider"
    }, 
    {
    "host": "asd",
    "port": 136,
    "protocol": "fg"
    } <-- These are the TcpDevice POJOs
    ]
}

Now I have the Wrapper POJO available and need to change this wrapper pojo to the actual Object I need which is defined in the JSON itself.

Here is an example code:

ObjectMapper mapper = new ObjectMapper();
JsonFactory f = mapper.getFactory();
File jsonFile = new File( filePath );

try ( JsonParser p = f.createParser( jsonFile ) )
{
  try ( MappingIterator<TcpDeviceWrapperImpl> deviceWrappers = mapper.readValues( p, TcpDeviceWrapperImpl.class ) )
  {
    while ( deviceWrappers.hasNext() )
    {
      TcpDeviceWrapper devicewrapper = deviceWrappers.next();
      List<TcpDeviceImpl> devices = devicewrapper.getDevices();
      for ( TcpDevice device : devices )
      {
        String protocol = device.getProtocol();
        switch ( protocol )
        {
          case TcpProtocols.BERST:
            break;
          case TcpProtocols.CMT:
            break;
          case TcpProtocols.FG:
            break;
          case TcpProtocols.SCT:
            break;
          case TcpProtocols.HÜLSENSÄGE:
            break;
          case TcpProtocols.ROLLENSCHNEIDER:
            RollCutterDevice rollCutter = (RollCutterDevice) devicewrapper;
            cxManager.addDevice( rollCutter.getName(), rollCutter );
            break;
          default:
            break;
        }
      }
    }
  }
}

Naturally the cast I performed in the switch-case is not working.

I know that I could research Reflection to perform the task I need ( not sure if that would work though ), but I also know that this way of doing things is not good. I would like to avoid using reflection.

Now I am asking how I can cast the POJO for TcpDevice to the actual Implementation I need. The fields are all the same with the only exception that the other protocols have additional functions.





How could I export class information and turn it into a syntax helper from a closed application?

I'm coding in an application that has built in editor and the module only available for internal use, so it doesn't allow me to reference it in Visual Studio and code outside its environment.

What would be the best way to export that class information from within to a documentation which I could then just import into VS and use as syntax helper?

I thought of using reflection and write it in xml, is there any better way?





Scala reflection. Is there a convenient way to verify that reflection class is module class (companion object)?

I'm trying to find out if the class is an implementation of a companion object, or it's a regular class that corresponds to some type of data.

def checkIsCompanionClass(universe:scala.reflect.api.Universe, class:Class[_]):Boolean = {
    val classSymbol = universe.rootMirror.staticClass(cls.getName)
    classSymbol.isModule //or classSymbol.isModuleClass
}

I tried this, but isModule and isModuleClass return false for "companion" classs (class name ends with $)





jeudi 27 juillet 2017

Android getDeclaredFields() return a disorder result

I declared a class like this:

public class Bean {
    public int id;
    public String name;
    public int age;
}

I use Bean.class.getDeclaredFields() to get the fields of Bean.class. The standard JRE on PC returned

  • id,
  • name,
  • age

fields. But the same code running on Android (4.1.2 Dalvik JVM), the result fields order is

  • name,
  • age,
  • id.

I noted that the implementation of getDelclaredFields() in Android is changed. It may be impossible to change the behavior. But I still want to known that how to get the ordered fields result.





Going through every object in program using reflection

I want to write a cost analysis method for a number of different classes that would count the number of times certain objects have been created. The easy way would be to increment a variable in the constructors for each of them, but I was wondering if it's possible to just go through every object currently in use using reflection?





How do I access a subclass's const property value with reflection (null reference)?

Poor practice aside, I'm trying to get filter subclasses by their property values.

class Base
{
const string tag = "";
}

class A : Base
{
new const string tag = "ClassA";
}

class B : Base
{
new const string tag = "ClassB";
}

I know that const is implicitly static, and so the tags aren't actually inherited, but instead are just associated with the subclasses.

Then, I want to filter to only Class A:

var result = Assembly.GetAssembly(typeof(Base))
.GetTypes()
.Where(t => t.BaseType == (typeof(Base))
.Where(t => ((string)t.GetProperty("tag").GetValue(null)).ToLower() == "classa")
.FirstOrDefault()

I'm calling GetValue on null because as a static property, I shouldn't call GetValue on an instance. This is from Get value of a public static field via reflection

When I run this code, I get a NullReferenceException. This is not an ideal way of doing this, but I am constrained to getting by assembly and comparing by string. Why would I be getting the null reference?





Method.invoke not working with package-private class

I have a class TableModelBase that extends AbstractTableModel. In there I override the getValueAt method so that it return the getter result of the row class.

TableModelBase.java

@Log
@AllArgsConstructor
public abstract class TableModelBase<T> extends AbstractTableModel{
    @NonNull private final String[] columns;
    @NonNull protected final transient List<T> rows;

    //...

    /**
     * Default getValue method.<br>
     * The row type fields must be in the same sequence that the columns.<br>
     * Getter methods must follow the getter convention.
     * @param rowIndex The row index.
     * @param columnIndex The column index matches the field index of the row type.
     * @return Object
     */
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        final T row = rows.get(rowIndex);
        if(row.getClass().getDeclaredFields().length != getColumnCount()) {
            for (Field field : row.getClass().getDeclaredFields()) {
                System.out.println(field.getName());
            }
            log.severe("Fields number and table columns number are different in: " + row.getClass().getSimpleName());
            System.exit(1);
        }
        final Field field = row.getClass().getDeclaredFields()[columnIndex];

        String getter;
        if(field.getType().equals(boolean.class)) {
            getter = field.getName();
        }
        else {
            getter = "get" + Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
        }

        try {
            Method method = row.getClass().getMethod(getter);
            return method.invoke(row);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            log.severe(e.getMessage());
            System.exit(1);
            return null;
        }
    }
}

I have a test class TableModelTest in the package tablemodel. In this package there is also the classes Data and DataModel.

Data.java

@Value
class Data {
    String text = "text";
    boolean isSuccessful = true;
}

DataModel.java

class DataModel extends TableModelBase<Data> {
    DataModel() {
        super(new String[]{"Text", "Is Successful"}, new ArrayList<>());
        rows.add(new Data());
    }
}

TableModelBaseTest

public class TableModelBaseTest {
        @org.junit.Test
        public void getValueAt() {    
            final DataModel dataModel = new DataModel();
            assertEquals("text",dataModel.getValueAt(0, 0));
            assertEquals(true, dataModel.getValueAt(0, 1));
        }
}

The test give an IllegalAccessException:

Class com.dsidesoftware.tablemodel.TableModelBase can not access a member of class tablemodel.Data with modifiers "public"

The getters are public so why I cannot access them ?
The strange thing is when I make Data public, the exception is gone.

Any idea of what is going on ?

Thanks.





Create a generic function that return a generic type list in C#

I have two Model classes, one is Person and the other is Department. What I want to achieve is I want to create a generic function which can be used to retrieve generic type data in the form of List for e.g. one call will return Person List , another call will return Department List. More specifically I want to return data in the form of a List.

The below is the Person Class.

public class Person {

    public Int16 Personid{ get; set; }
    public string Personname { get; set; }
    public string Personaddress { get; set; }

}

The below is the Department class.

public class Department {

     public Int16 Departmentid { get; set; }
     public string Departmentname { get; set; }
     public string Departmentsection { get; set; }

}

The below are the calling function where One time I make a call with CallingMethodPerson() and other with CallingMethodDepartment().

public class CallingClass {

   public void CallingMethodPerson() {

      CalledClass calling = new CalledClass();
      Calling. CalledMethod();

   }

    public void CallingMethodDepartment() {

      CalledClass calling = new CalledClass();
      Calling. CalledMethod();

    }
}

The below blue print is the CalledClass where it does some manipulation and return List of either Person or Department.

public class CalledClass {

    public void CalledMethod() {
      //this is a generic method wherein returns the list of either a Person 
      or Department whenever called.

    }
}

To summarise I want to implement a common function that return generic type data.





Creating new instances for objects in dictionary

I made project Animal and set it as Library. Of course in Animal project I'll add more classes. In this project I have 2 classes for now: Dog and Method.

//Class Method
public class Method : Attribute{
    public string Name { get; set; }
    public Method(){
        Name = "";
    }
}

//Class Dog
[Method(Name = "dog")]
public class Dog
{
    public int NumberOfLegs { get; set; }
    public string Breed { get; set; }
    public Dog() { }
}

Then I created second project in my solution Ref and it is my main class:

//version 1
class Program{
    public static Dictionary<String, Type> animals;
    static void Main(string[] args){
        Assembly assembly = Assembly.GetEntryAssembly();
        Type[] typ = assembly.GetTypes();
        foreach (Type t in typ){
            animals.Add(t.Name, t);
        }
    }
}

I want achieve "dog, Dog", "cat, Cat", "rat, Rat". Where "dog" is name attribute and "Dog" is a type thanks to I will be able to make something like

Activator.CreateInstance(animals[nameAnimal]);

But for now I do something wrong, my way doesn't work and I cannot find working solution for my problem in .net core. I want only object from classes where is Attribute Method. How achieve it?





mercredi 26 juillet 2017

Instantiate a Java type parameter/ generic using a Class object

How do you instantiate a Java generics Object that takes type parameters given only a Class or Class<?> object?

For example: Normally one can instantiate an ArrayList of Integer objects using the following syntax:

ArrayList<Integer> foo = new ArrayList<Integer>();

However, given a Class<?> object such as Integer.class, how could one create a similar ArrayList? For example, how would I do something like this (incorrect syntax):

ArrayList<Integer.class> foo = new ArrayList<Integer.class>();

I need this for something very unusual I am doing with Java (Creating an open-source tool for visualizing user-supplied instances of data structure/ generic classes they write). Here is an example of how I would be using this code which illustrates the information I would be given:

import java.util.ArrayList;
import java.util.List;

public class ArrayListFromClass {
    // obviously this code does not work
    public static void main(String[] args) {
        Object givenObject = new Integer(4);
        // I would not know it is Integer.class, a Class<?> object would be supplied by the user/ as a generic
        Class<?> cls = givenObject.getClass();
        List<cls> bar = new ArrayList<cls>();

        // Where args[0] is "Integer.class"
        List<args[0]> foo = new ArrayList<args[0]>();

        // then I would be able to add to foo or bar with one or both of these techniques:
        // printing givenObject.getClass() gives you java.lang.Integer, don't worry about the casting not working.
        bar.add(cls.cast(givenObject));
        Integer y = 6;
        bar.add(y);
    }
}





Why does Method Invoke fail with argument exception?

Consider this code sample from a WinForms app:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            object[] parms = new object[1];
            parms[0] = "foo";

            DoSomething(parms);
        }

        public static string DoSomething(object[] parms)
        {
            Console.WriteLine("Something good happened");
            return null;
        }
    }

It works as expected, when you click button1 it prints "Something good happened" to the console.

Now consider this code sample, which is the same except that it invokes DoSomething using reflection:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            object[] parms = new object[1];
            parms[0] = "foo";

            System.Reflection.MethodInfo mi = typeof(Form1).GetMethod("DoSomething");
            mi.Invoke(null, parms);

        }

        public static string DoSomething(object[] parms)
        {
            Console.WriteLine("Something good happened");
            return null;
        }
    }

It throws an System.ArgumentException on the line mi.Invoke(null, parms) (Object of type 'System.String' cannot be converted to type 'System.Object[]'.)

parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array. So why is invoke pulling the first object out of the array and trying to pass that instead?

Or is something else going on that I'm not understanding?





when to use CPS vs codensity vs reflection without remorse in Haskell

Are there any rules of thumb for when to use continuation-passing style vs codensity vs reflection without remorse when creating monads in Haskell?

As an example, I'm going to use a simple coroutine monad. If you've never seen this before, you might want to check out the "Coroutine Pipelines" article in Monad.Reader Issue 19 or the pipes library. The full code for the following examples can be found in this repository.

  1. Normal

    This is just a normal monad defined as a datatype:

    data FooM i o a
      = Await (i -> FooM i o a)
      | Yield o (FooM i o a)
      | Done a
    
    

    This style is used extensively thorought the Haskell ecosystem. One example of this style is the Proxy data type from pipes.

  2. Continuation-Passing Style (CPS)

    This is similar to the normal style, but each data constructor has become an argument to a continuation:

    newtype FooCPS i o a = FooCPS
      { runFooCPS
          :: forall r.
             ((i -> FooCPS i o a) -> r)
          -> (o -> FooCPS i o a -> r)
          -> (a -> r)
          -> r
      }
    
    

    This style is used in both attoparsec and parsec.

  3. Codensity

    This style uses a codensity monad transformer wrapped around a monad defined in the normal style. This gives O(1) left-associative bind.

    The codensity monad transformer looks like the following:

    newtype Codensity m a = Codensity
      { runCodensity :: forall b. (a -> m b) -> m b
      }
    
    

    Our actual monad could be defined as a newtype using the Codensity transformer. Notice how FooCodensity is using FooM internally.

    newtype FooCodensity i o a = FooCodensity
      { runFooCodensity :: Codensity (FooM i o) a
      }
    
    

    This style is used by conduit in the ConduitM type.

  4. Reflection without Remorse

    This is the style discussed in the paper Reflection without Remorse.

    This is similar to the normal style, but recursive calls have become a data structure with O(1) append and amortized O(1) uncons. This gives O(1) left-associative bind and monadic-reflection to the FooRWR monad:

    data FooRWR i o a
      = AwaitRWR (forall x. i -> FooExplicit i o x a)
      | YieldRWR  o (forall x. FooExplicit i o x a)
      | DoneRWR a
    
    

    The FooExplicit type is defined as the following:

    type FooExplicit i o = FTCQueue (FooRWR i o)
    
    

    FTCQueue is a data structure with O(1) append and amortized O(1) uncons.

    This style is used by the freer-effects and extensible packages. It is available as a standalone library in monad-skeleton.


When should normal vs CPS vs codensity vs reflection without remorse be used? I imagine a hard and fast answer would require benchmarking a given monad and application, but are there any rules of thumb?

From my own research, I've come across the following ideas/comments:

  • CPS can be faster than normal style because you may not have to do case-analysis. Although the actual speedup may vary based on how the code is compiled by GHC. Codensity and reflection without remorse have some overhead.

    Gabriel Gonzalez (the author of pipes) writes about how he sticks with normal style for pipes in both this reddit thread and this issue on Github.

    Byran O'Sullivan (the author of attoparsec) writes about how changing attoparsec from normal style to CPS gave a factor of 8 speedup. Some of the comments on that post also talk about normal style vs CPS.

  • If you need deep left associative binds, normal style and CPS end up with quadratic runtime.

    Here is an example from the "Reflection without Remorse" paper that will exhibit quadratic runtime.

    data It i a = Get (i -> It i a) | Done a
    
    sumInput :: Int -> It Int Int
    sumInput n = Get (foldl (>=>) return (replicate (n - 1) f))
      where
        f x = get >>= return . (+ x)
    
    

    If sumInput is rewritten with codensity or reflection without remorse, it will run perfectly fast.

    If your application has deep left-associative binds, you should probably be using codensity or reflection without remorse.

    Michael Snoyman (author of conduit) talks about this in a blog post about speeding up conduit.

    The pipes library used to provide a codensity transformer.

  • CPS and codensity don't support O(1) reflection.

    Here is a function that requires monadic reflection. This example is adapted from the "Reflection without Remorse" paper:

    data It i a = Get (i -> It i a) | Done a
    
    par :: It i a -> It i b -> It i (It i a, It i b)
    par l r
      | Done <- l = Done (l, r)
      | Done <- r = Done (l, r)
      | Get f <- l, Get g <- r = Get Done >>= \x -> par (f x) (g x)
    
    

    This method can't be written in the CPS or codensity style without first converting back to normal style. The reflection without remorse style does not have this problem.

    If you need monadic reflection, you should probably be using normal style or reflection without remorse.

  • Reflection without remorse adds some overhead, but it is the only style that gives both O(1) left-associative bind and reflection.

bonus question: A similar question could be asked about Free (normal style) vs F (CPS) from the free package. When should Free be used? When should F be used?





Get closure information from Java functional interface

I'd like to be able to access closure environment information at runtime from a Java functional interface. For example, I'm passing in a lambda, say, (input) -> input + knownVariable to a function lambdaProcessor.

Now, from within lambdaProcessor, I'd like to be able to access the environment associated with this lamdba, and get the value of all the variables stored in this environment.

Is this possible? I don't mind having to create my own functional interface, or use reflection, etc.





WPF + Reflection + Console output are not working

I develop an WPF application, which using reflection to load other-side .NET assembly "Cons.dll". This loaded assembly is a console application. I see in debugger, that methods from this DLL are do their work. But I cannot see its Console output.

If I forced show console from my WPF app using imported function "AllocConsole" from "kernel32.dll", other-side "Cons.dll" are not puts its output to this console.

So question is how can I use other-side console assembly from main WPF application, and see its console output?





How to determine (at runtime) if a variable is annotated as deprecated?

This code can check whether a class is deprecated or not

@Deprecated
public classRetentionPolicyExample{

             public static void main(String[] args){  
                 boolean isDeprecated=false;             
                 if(RetentionPolicyExample.class.getAnnotations().length>0){  
                     isDeprecated= RetentionPolicyExample.class  
                                   .getAnnotations()[0].toString()
                                   .contains("Deprecated");  
                 }  
                 System.out.println("is deprecated:"+ isDeprecated);             
             }  
      }

But, how can be checked if any variable is annotated as deprecated?

@Deprecated
Stringvariable;





Getting model type from expression

I'm trying to use reflection to get the model type. So far I was able to get the type of property. But when I tried to use expression to get model type, I'm getting null reference for that property.

//How I'm getting property name, I'm passing model with expression
MemberExpression expBody = expression.Body as MemberExpression;
model.GetType().GetProperty(expBody.Member.Name.ToString()));

Is it possible to do something like this?

MemberExpression expBody = expression.Body as MemberExpression;
    expBody.Type.GetProperty(expBody.Member.Name.ToString()));

I tried this, but not working.





How does Netty find type parameters

In the last few month I played a bit with netty and I was impressed. If I add a SimpleChannelInboundHandler<T> to the pipeline, it will get notified only for inbound events of type T. I seems like the class io.netty.util.internal.TypeParameterMatcher has something to do with it - but it has no documentation.

So, how does Netty achieve this?





How create a instance of class with dependent in constructor from startup.cs(ASP.NET Core)

I'm trying to create email client in my asp.net core web application.I have created a class with some DB service as dependent and I have a method inside this class which will connect to the mail box and starts listening to it on a separate thread.But I'm unable to create an instance of the class from the startup.cs file because I unable pass IDBxxxxService to the constructor.

  var serviceProvider = Services.BuildServiceProvider();
        serviceProvider.CreateInstance<MailEvents>().MailSubscribe(new IMAPConnection
        {
            Host = "imap.gmail.com",
            EnableOAuth = false,
            Port = 993,
            EnableSSL = true,
            UserName = "xxxxxxxxxxx",
            Password = "9xxxxxxxxxxxxxx",
        });

and here is extension method i have written to create the instance using reflection.

public static TResult CreateInstance<TResult>(this IServiceProvider provider) where TResult: class
    {
        ConstructorInfo constructor = typeof(TResult).GetConstructors()[0];

        if (constructor != null)
        {
            object[] args = constructor
                .GetParameters()
                .Select(o => o.ParameterType)
                .Select(o => provider.GetService(o))
                .ToArray();

            return Activator.CreateInstance(typeof(TResult), args) as TResult;
        }

        return null;
    }





Display the method annotations available in a java class using Java reflection

I am currently working on a java project that needs to display the meta information of a java class like the annotations that have been declared for methods, parameters, etc.

I have the following classes

Employee.java

package labsheet;

public class Employee {

    private String eid = "E001";
    String ename = "Anura";
    public String address = "Batticaloa";
    protected double salary = 60_000.00;

    public String getEid() {
        return eid;
    }
    public void setEid(String eid) {
        this.eid = eid;
    }
    String getEname() {
        return ename;
    }
    void setEname(String ename) {
        this.ename = ename;
    }
    protected String getAddress() {
        return address;
    }
    protected void setAddress(String address) {
        this.address = address;
    }
    @SuppressWarnings("unused")
    private double getSalary() {
        return salary;
    }
    @SuppressWarnings("unused")
    private void setSalary(double salary) {
        this.salary = salary;
    }

    public String display(String eid, String ename, String address, double salary){
        System.out.println("Method invoked successfully");
        return eid+" , "+ename+" , "+address+" , "+salary;
    }


}

In my main class Task3.java I am trying to display the annotations that are available in the Employee.java. And hence I intend to display the @SuppressWarnings("unused") details for the methods getSalary() and setSalary() using Java Reflection.

I have currently coded the Task3.java as follows.

Task3.java

package labsheet;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;

public class Task3 {
    public static void main(String[] args) {
        try {
            Class<?> clazz = Class.forName("labsheet.Employee");
            Method[] methods = clazz.getDeclaredMethods();

            for(int m =0; m<methods.length;m++){
                System.out.println("Modifier=> "+ Modifier.toString(methods[m].getModifiers()));
                Annotation [] annotations = methods[m].getAnnotations();
                System.out.println("Annotation count: "+annotations.length);
                for(int o =0; o<annotations.length;o++){
                    System.out.println("Annotation "+(o+1)+": "+annotations[o]);
                }
                System.out.print("|| Return Type=> "+ methods[m].getReturnType());
                System.out.print("|| Method Name=> "+ methods[m].getName());
                Parameter[] parameters = methods[m].getParameters();
                if(parameters.length != 0){
                    System.out.print("|| Method Parameters=> ");
                    for(int u = 0; u<parameters.length;u++){
                        if(u== parameters.length-1){
                            System.out.print(parameters[u].getType().getSimpleName());
                        }
                        else{
                            System.out.print(parameters[u].getType().getSimpleName()+" ");
                        }
                    }
                }

                System.out.println();
                System.out.println();
            }
            System.out.println("*******************************");
            executeMethod();
            System.out.println("*******************************");
            executeMethodWithDefault();
        } 

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

    }

...
//Methods declaration for executeMethod() and executeMethodWithDefault()

}

But I am getting an output where it says that there are no annotations for the getSalary() and setSalary() methods as well, whereas I need the @SuppressWarnings("unused") annotation details to be displayed here.

Output

Modifier=> protected
Annotation count: 0
|| Return Type=> class java.lang.String|| Method Name=> getAddress

Modifier=> public
Annotation count: 0
|| Return Type=> class java.lang.String|| Method Name=> display|| Method Parameters=> String String String double

Modifier=> private
Annotation count: 0
|| Return Type=> void|| Method Name=> setSalary|| Method Parameters=> double

Modifier=> 
Annotation count: 0
|| Return Type=> class java.lang.String|| Method Name=> getEname

Modifier=> protected
Annotation count: 0
|| Return Type=> void|| Method Name=> setAddress|| Method Parameters=> String

Modifier=> 
Annotation count: 0
|| Return Type=> void|| Method Name=> setEname|| Method Parameters=> String

Modifier=> private
Annotation count: 0
|| Return Type=> double|| Method Name=> getSalary

Modifier=> public
Annotation count: 0
|| Return Type=> class java.lang.String|| Method Name=> getEid

Modifier=> public
Annotation count: 0
|| Return Type=> void|| Method Name=> setEid|| Method Parameters=> String

Any suggestions in this regard will be much appreciated.





mardi 25 juillet 2017

How can I emit a dynamic method returning a ref?

I'm navigating the ins and outs of ref returns, and am having trouble emitting a dynamic method which returns by ref.

Handcrafted lambdas and existing methods work as expected:

class Widget
{
    public int Length;
}
delegate ref int WidgetMeasurer(Widget w);

WidgetMeasurer GetMeasurerA()
{
    return w => ref w.Length;
}

static ref int MeasureWidget(Widget w) => ref w.Length;
WidgetMeasurer GetMeasurerB()
{
    return MeasureWidget;
}

But emitting a dynamic method fails. Note: I'm using Sigil here. Apologies, I'm less familiar with System.Reflection.Emit.

WidgetMeasurer GetMeasurerC()
{
    FieldInfo lengthField = typeof(Widget).GetField(nameof(Widget.Length));
    var emitter = Emit<WidgetMeasurer>.NewDynamicMethod()
        .LoadArgument(0)
        .LoadFieldAddress(lengthField)
        .Return();
    return emitter.CreateDelegate();
}

This fails at NewDynamicMethod, throwing 'The return Type contains some invalid type (i.e. null, ByRef)'. Which makes sense, since I understand that under the hood WidgetMeasurer returns an Int32&.

The question is, is there some first- or third-party technique I can employ to emit code mimicking the first two examples (which I empirically know work correctly)? If not, is this restriction a logical one?





Golang get struct tag without pointer

i was creating a simple marshaler for fixed with text into struct in golang, as detailed here http://ift.tt/2uwcqod

The marshaler functions as I expected now, albeit still lacking some features. What I got stuck in is in the marshal function.

The relevant code is as follow

func Marshal(obj interface{}) (str string, err error) {
...
    elemsType := reflect.TypeOf(obj).Elem()

As you can see, i tried to mimic the json package's marshal signature. Then only problem is when i tried to pass by value to the marshal function, the reflect.TypeOf returns a different type than the one i pass into it. The function can only executed if I'm passing pointer to the marshal function.

This works user := User{"johnjohnjohn", "the", "doe", "smart", 26} res, err := Marshal(&user)

This doesn't user := User{"johnjohnjohn", "the", "doe", "smart", 26} res, err := Marshal(user)

Is there any way to just pass by value, and then get the struct tag inside the marshal function?





Scala. How to Infer generic type inside class inheritance

I have two classes:

class Base[A]{
    def doSome:A
}

class StringImpl extends Base[String]

How can I infer (without manifest, only reflection analysys) that generic type A inside class StringImpl is a String? (In real case Iheritance structure may by match more complex that example)





Class not included during sbt assembly

i try to create a fat jar using the sbt assembly plugin. While importing several (problem-unrelated) dependencies in commonSetting with scala version 2.11.8, the build.sbt looks as follows:

lazy val root = (project in file("."))
    .settings(commonSettings: _*)
    .settings(
    name := "stream",
    mainClass in Compile := Some("stream.Streaming"),
    mainClass in assembly := Some("stream.Streaming"),
    assemblyJarName in assembly := "spark.jar",
    assemblyMergeStrategy in assembly := {
        case PathList("javax", "servlet", xs@_*) => MergeStrategy.first
        case PathList("META-INF", "io.netty.versions.properties") => MergeStrategy.last
        case PathList(ps@_*) if ps.last endsWith ".html" => MergeStrategy.first
        case "application.conf" => MergeStrategy.concat
        case "reference.conf" => MergeStrategy.concat
        case m if m.toLowerCase.endsWith("manifest.mf") => MergeStrategy.discard
        case m if m.toLowerCase.matches("meta-inf.*\\.sf$") => MergeStrategy.discard
        case _ => MergeStrategy.first
    },
    test in assembly := {}
)
.enablePlugins(AssemblyPlugin)

This assembles just fine and includes (almost) everything I need. I only have one missing class in the scala.reflect library. Generally, the reflect library is included with the correct version and sbt run does not have any problems.

The failing class of my code throwing Exception in thread "main" java.lang.NoClassDefFoundError: scala/reflect/api/JavaUniverse imports scala.reflect.runtime.universe which is a lazy val created like this in scala-reflect_2.11.8 (scala.reflect.runtime.package$.class)

package scala
package reflect

package object runtime {
    lazy val universe: api.JavaUniverse = new runtime.JavaUniverse
...

Sbt now does not include the necessary class scala.reflect.api.JavaUniverse even if I import it and declare the necessary lazy val as val uv: JavaUniverse = universe in the failing class. Although sbt does include a class with the same name in a different package being: scala.reflect.runtime.JavaUniverse.

Could this be a name conflict? Or is the problemin the package$.class not defining package api outside the package object?

Is there a way in sbt to manually declare a class to be included? Or any other workaround?

Any help is appreciated!





getTypesAnnotatedWith returns classes without annotation

I'm trying to use class annotations in Java, and I have the strange behaviour where getTypesAnnotatedWith returns a class on which getAnnotation returns null.

Is there some reason getTypesAnnotatedWith returns classes without annotation?

For example, in my project the following piece of code returns (correctly) one of the classes I annotated:

new Reflections("my.nice.package")
    .getTypesAnnotatedWith(MyTag.class)
    .iterator().next();

However, if I call getAnnotation on it, the result is null:

new Reflections("my.nice.package")
    .getTypesAnnotatedWith(MyTag.class)
    .iterator().next()
    .getAnnotation(MyTag.class));

This is the annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyTag {
    public String value();
}

and, for completeness, this is how I annotate classes:

@MyTag("FooBar")
class MyClass {
    // ...
}





lundi 24 juillet 2017

Construct a custom object whose properties will be enumerated in the order in which they were defined

I have an object that I created in PowerShell to fetch info from AWS.

$list = New-Object -TypeName PSObject -Property @{
  'name'          = ($instance.Tags | Where-Object {$_.Key -eq 'Name'}).Value
  'baseAmi'       = ""
  'patchDate'     = ""
  'baseName'      = ""
  'owner'         = ($instance.Tags | Where-Object {$_.Key -eq 'Owner'}).Value
  'instanceID'    = $instance.InstanceID
  'imageID'       = $instance.ImageId
  'env'           = ($instance.Tags | Where-Object {$_.Key -eq 'EnvName'}).Value
  'instanceState' = $instance.State.Name
}
$baseAmi = Get-EC2Image -ImageId $list.imageID
$list.baseAmi = ($baseAmi.Tags | Where-Object{$_.Key -eq 'BaseAmi'}).Value
$baseAmi = Get-Ec2Image -ImageId $list.baseAmi
$list.patchDate = ($baseAmi.Tags | Where-Object{$_.Key -eq 'PatchDate'}).Value
$list.baseName = ($baseAmi.Tags | Where-Object{$_.Key -eq 'Name'}).Value

I would like to output the fields of the object in the following order:

baseName,baseAmi,patchDate,name,owner,instanceID,env,instanceState

This object is then exported as a CSV. I basically need the CSV headers to be organized in that order when viewing it in Excel.





Simpler way of accessing custom attributes?

I have a property of the "Form1" class called "InfoTest" that has some custom attributes that I want to access.

The code works fine, but is a bit unwieldy:

[Test("foo",15)]
    public double InfoTest { get; set; }

    public void RetrieveAttribute()
    {
        PropertyInfo field_info = typeof(Form1).GetProperty("InfoTest");
        object[] custom_attributes = field_info.GetCustomAttributes(typeof(TestAttribute), false);
        TestAttribute thisAttribute = (TestAttribute)custom_attributes[0];
        Debug.WriteLine(thisAttribute.Info + "," + thisAttribute.TheValue);
    }

I presume the answer is "No", but is there a simpler way of getting the attributes for InfoTest, that doesn't involve the `typeof(Form1).GetProperty("InfoTest")? I can't go (for example):

    var runtimePropInfo = InfoTest.GetType().GetRuntimeProperties();
    var propInfo = InfoTest.GetType().GetProperties();

...Which is essentially because it is trying to get the properties of a "double", not a "InfoTest" object.





can yaml have method names as values

I am using an yaml file which looks like :

TestCase1:   # Updating age to 56
startDate/inner/inner2/age: 56
  startDate/$date: "2017-07-20T19:00:00.000Z"
  name: "SomeOne"

TestCase2:   #Updating Age to 45
  startDate/inner/inner2/age: 45

Can I do something like :

  startDate/inner/inner2/age: 56
  startDate/$date: ${MethodToGetCurrentDate}
  name: ${MethodWhichReturnSomeName}

I am looking to parse this yaml and while doing so look for pattern like ${method Name } and that method is called using reflection and the method returns the value.

Is it doable? I am using scala.





how to check if a Windows.Form is empty but not null?

I have a function which returns an instance of Windows Form

   `public Form getForm(string Node)
   {
   Form obj = new Form();

   obj = (Form)Activator.CreateInstance(Node);
   return obj;
   }`

I am Calling this function as :

   Form requestedForm = new Form(); 
   requestedForm = getForm(system);
   if ((requestedForm != null) && (requestedForm.Text!=""))
   // to check if the Form is not empty.
   {
    openform(requestedForm);
   }        
   else
   {
    MessageBox.Show("No form Found");
   }        

In Some Cases i get requestedForm.Text="" even if the form is not blank so how do i check this ?

Any help would be deeply appreciated





Generic Data Set

I need to make general class for transform Tuple data, to Data Set. Is possible to call "unknown data method's" with different return type. For example <Tuple<List<string,int>>, <Tuple<List<int,int>> and put it in like generic type?

I have a generic Class

static class Helper<T>
{
    public static DataSet Transform(T data)
    {
        ...transform logic
        return new DataSet();
    }
}

And another class, which call diferent methods, which return diferents types.

For example i call method which return this type: Tuple<List<Tuple<long, string, string>>, List<Tuple<long, string, string>>> and i try to call geneeric class method Transform and insert specific date type, which i get from method result by GetType(). But i have problem with it.

For Example - this work, i set string like generic type and string content.

Helper<string>.Transform("test");

But if i want to use "unknown" type, i don't know, how i put it like date type.

var data = Data.GetData();
var type = data.GetType();
//this doesn't work
Helper<type>.Transform(data);

I hope so my question is clear.

Thanks for your help.





Invoke method with parameters

I have a problem with reflection.

The very essence: there is a bunch of methods in the class. I find it necessary this way (it's all good here):

invokingMethod = InstanceClass.getMethod(AMethodName, AArgumentTypes);

Then I want to call him:

result = invokingMethod.invoke(AInstance, AArgumentObjects);

The number of parameters can be different. Here, simply calling the authorization method and therefore only two parameters Content AArgumentObjects:

enter image description here

And as a result I have an error about the wrong type of parameters passed.

Works only if you explicitly pass all parameters to a function. Or I use AArgumentObjects[1] in the debug menu variable (if I change it in the code, the errors remain):

enter image description here

After calling from the code with AArgumentObjects[1]:

Discharges : "java.lang.IllegalArgumentException"





.NET: Custom assembly resolution failing when loading resources

I have a project which needs to load extra assemblies dynamically at runtime for reflection purposes. I need custom code because the path to the DLLs is not known by the framework. This code works fine with normal DLLs, they load fine and I can reflect over them. However, when I attempt to load types which statically uses embedded resources (i.e. a resx) this code fails.

Without my custom assembly resolution code this works fine. Here is my assembly resolution code:

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    bool isName;
    string path = GetAssemblyLoadInfo(args, out isName);
    return isName ? Assembly.Load(path) : Assembly.LoadFrom(path);
}

static string GetAssemblyLoadInfo(ResolveEventArgs args, out bool isAssemblyName)
{
    isAssemblyName = false;
    var assemblyName = new AssemblyName(args.Name);
    string path = String.Concat(new FileInfo(DllPath).Directory, "\\", assemblyName.Name, ".dll");
    if (File.Exists(path))
    {
        return path;
    }
    if (path.EndsWith(".resources.dll"))
    {
        path = path.Replace(".resources.dll", ".dll");
        if (File.Exists(path)) return path;
    }

    var assemblyLocation = AssemblyLocations.FirstOrDefault(al => al.Name.FullName == assemblyName.FullName);
    if (null == assemblyLocation)
    {
        isAssemblyName = true;
        return args.Name;
    }
    else
    {
        return assemblyLocation.Location;
    }
}

Here is a link to a project which recreates the entire issue:

http://ift.tt/2ttSP6R

Once you download the project and run it it should work fine and write the string "This is the value of the resource" to the console, which comes from the resx file. However, uncomment line 23 in Program.cs and run it again and it will fail with an exception, which indicates that it failed to load the embedded resources.





C++: get superclasses type index from type index

I have a template type T, that subclasses Base (must not be directly). By using

std::type_index(typeid(T)),

I can get a metadata object for T. Is there a way to get a std::type_index for every superclass of T, so that I can traverse the superclasses upwards until Base is reached?

I know C++ doesn't provide reflection by itself, but maybe someone knows some template magic.

In detail: I want to put pointers of objects into a map, indexed by the objects type. It would be nice to be able to insert the objects not just as their own type, but as their supertypes, too.





Switch mongodb classes definition during runtime

I'm using mongodb (driver 3.4.2) with spring framework (spring-data-mongodb:1.10.4) and I want to achieve funcionality to switch mongo data definition during runtime.

So far I've written classloader and I'm passing it to mongo. My problem is that after loading initial jar's from classloader, when I change jar, new classes definition aren't being loaded ( loadClass from classloader is not called for those classes).

My guess is that mongo caches initially loaded classes, so after loading new jar I was trying a bit blindly clearing different collections of classes in MongoTemplate using reflection, so far without success.

How I can force mongodb to load again classes with same name?





dimanche 23 juillet 2017

Dynamically casting object type to specific class type using reflection

I have many Cog classes are all similar, and I need to add them to parameterized lists of type Cog based on the class path.Cog_1, Cog_2,..., Cog_N. Is there anyway to use reflection to cast an Object type to specific Cog class if I have the path?

main(){
List<Cog> CogList = LIsts.newArrayList();
List<Cog_2> CogList_2 = LIsts.newArrayList();

CogList.add(createObject("path.to.Cog");
CogList_2.add(createObject("path.to.Cog_2");

Class<?> clazz3 = Class.forName("path.to.Cog_3");
//CogList_3.add(clazz3.cast(result);  Error add (Cog_3) to list cannot be applied to capture <?>
}

public Object createObject(String classPath){
Class<?> clazz = Class.forName(classPath);
Constructor<?> cons = clazz.getConstructor();
return  Object object = cons.newInstance();
}

I'd rather have not have to manually cast each object to type. It works, but but would add in a lot of boiler plate code.

if (result instanceof Cog_10){
 (Cog_10) clazz.cast(result)
}





how to read runtime annotations on a field within a class

Imagine an annotation called "MyAnn" with runtime retention, a class MyClass, and an abstract class called MyData. MyClass has a field of type MyData, annotated with MyAnn. Within the instance of MyData, I need to see if the annotation MyAnn is present and retrieve its information?

Note - in Java8 I know we can directly annotate the inner class at construction - and that works - but I need this working based on the field annotation.

Thanks for any help!

public MyClass extends MySuperClass() {
   @MyAnn(value = "something")
   protected MyData mydata;

   public void doSomething() {
      mydata = new MyData() {};
      mydata.initialize();
   }
}

public abstract MyData() {
   String myValue = null;

   public void initialize() {
      if (***I am annotated with MyAnn) {
         myValue = (***value from annotation MyAnn);         
      }
   }
}

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnn {
    String myvalue;
}





How to get reverse owner relationship between symbols

Each Universe.Symbol has owner property that points to an owner symbol. How could I get reverse, i.e. list all symbols that consider given symbol as owner? I give documentation a glance, but could not find appropriate method.





Finding the most specific class in Java

I tried to write some kind of exception handler for my specific purposes. I have a list of classes. Let's say:

List<Class<? extends Throwable>> list = new LinkedList<>();
list.add(RuntimeException.class);
list.add(IllegalArgumentException.class);

Now, I want to do:

public Class<? extends Throwable> findMostSpecific(Class<? extends Throwable> type) {
     for (....) {
         if (... WHAT TO PUT HERE ? .... ) {
             return ....
         }
     }
}

this method has to find the most specific class of given type. So if I pass:

  • IllegalArgumentException, it has to find IllegalArgumentException (not RTE).
  • RuntimeException, it has to find RuntimeException
  • IllegalStateException, it has to find also RuntimeException (becuse IllegalStateException is not on the list)

So how to find the most specific type of a given instance? Is it possible?





c# remove all event handler from BackgroundWorker.DoWork by Reflection

i am helped by this link -How to remove all event handlers from a control

yep i succeed remove all event handler from control and form.

but i have failed in BackgroundWorker.

this is my code.

    void ReadingCompleted()
    {
        //find fields
        List<FieldInfo> liField=typeof(BackgroundWorker).GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Public).ToList();

        foreach(FieldInfo field in liField)
        {
            txtbox_log.Text += field.Name + "\r\n";
        }
        //below output list 
        //canCancelWorker
        //workerReportsProgress
        //cancellationPending
        //isRunning
        //asyncOperation
        //threadStart
        //operationCompleted
        //progressReporter
        //doWorkKey
        //runWorkerCompletedKey
        //progressChangedKey

        //remove all eventhandler
        object key = typeof(BackgroundWorker).GetField("doWorkKey", BindingFlags.NonPublic | BindingFlags.Static);

        EventHandlerList events = (EventHandlerList)typeof(Component)
        .GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance)
        .GetValue(this, null);
        events.RemoveHandler(key, events[key]);
        waitForm.Close();
    }





Php, get properties of object, except unset-ted

class Example
{
    private $fa, $fb;

    public function u()
    {
        unset($this->fb);
    }
}

$example = new Example();
$example->u();
foreach((new \ReflectionObject($example))->getProperties(\ReflectionProperty::IS_PRIVATE) as $v)
{
    echo '<pre>';
    var_dump($v);
    echo '</pre>';
}

it will print even fb although its been unsetted.





C#, How do I get back my object

public class testClass
{
    testClass x = null;
    public testClass()
    {
        x = this;
    }
    ~testClass()
    {
        System.Console.WriteLine("I was destroyed");
    }
}
public static class objectInMemory
{
    public static int Main(string[] args)
    {
        testClass a = new testClass();
        a = null;
        System.Console.WriteLine("a=null");
        System.Console.WriteLine("something");
        System.Console.WriteLine("last line");
        return 0;
    }
}

So.. In the code, how can I assign the instantiated testClass object to another variable after "a = null;" For example let "b = thatObject'sAddress;"?

It is not a problem, just came across my mind.





samedi 22 juillet 2017

Instantiating an unknown Object whose constructor takes a primitive array as an argument (reflection)

This program randomly instantiates any Object by recursively iterating through the parameters of a constructor until it finds a primitive or wrapper parameter that it can randomize. However, when a constructor takes a primitive array as a parameter, I get a

java.lang.IllegalArgumentException: argument type mismatch.

I have poured through Stack Overflow and the internet, but can't seem to find out how to feed a wrapper array into a constructor or turn a wrapper array into a primitive array.

I have considered the following methods of fixing this, but I am not sure of how to implement them:

  1. Create a custom subclass of java.lang.reflect.Constructor and change the getParameterTypes() method so that if a given parameter is a primitive array (such as int[]), change it to Integer[]. I think this may have some adverse effects however.
    1. Figure out how I can "add" items to varargs/ the Object[] parameterValues iteratively so that I can inspect each parameterValues[i] as I come across it, see if it is a wrapper array, then change it to a primitive array. This brings up the problem that a primitive array, such as a byte[], cannot go into the parameterValues that is fed into constructor.newInstance(parameterValues).

You may read all of the code if you'd like, however the two enums are not particularly relevant. The bulk of the action and my problem occurs in nextRandom(Class<?> cls) and some of it in randomBase(BASE_TYPE baseType).

Code:

import java.lang.reflect.*;
import java.util.Random;

/**
 * Sources used:
 * http://ift.tt/2eEQN16
   object-is-of-primitive-type
 * http://ift.tt/2gTGqr9
   contains-a-given-string
 * http://ift.tt/2eEOA5C
   random-number-in-java
 *
 * Created by Ward Bradt/ BlueOxile on July 22, 2017
 * http://ift.tt/2gTeh3c
 */ 
public class RandomGenerator {

    public enum BASE_TYPE {
        INTEGER (int.class, Integer.class),
        DOUBLE (double.class, Double.class),
        FLOAT (float.class, Float.class),
        LONG (long.class, Long.class),
        SHORT (short.class, Short.class),
        BYTE (byte.class, Byte.class),
        BOOLEAN (boolean.class, Boolean.class),
        CHAR (char.class, Character.class);

        private final Class<?> primitiveClass;
        private final Class<?> wrapperClass;

        BASE_TYPE(Class<?> primitive, Class<?> wrapper) {
            this.primitiveClass = primitive;
            this.wrapperClass = wrapper;
        }

        public Class<?> getPrimitiveClass() {
            return primitiveClass;
        }

        public Class<?> getWrapperClass() {
            return wrapperClass;
        }
    }

    public enum BASE_TYPE_ARRAY {
        INTEGER (int[].class, Integer[].class, BASE_TYPE.INTEGER),
        DOUBLE (double[].class, Double[].class, BASE_TYPE.DOUBLE),
        FLOAT (float[].class, Float[].class, BASE_TYPE.FLOAT),
        LONG (long[].class, Long[].class, BASE_TYPE.LONG),
        SHORT (short[].class, Short[].class, BASE_TYPE.SHORT),
        BYTE (byte[].class, Byte[].class, BASE_TYPE.BYTE),
        BOOLEAN (boolean[].class, Boolean[].class, BASE_TYPE.BOOLEAN),
        CHAR (char[].class, Character[].class, BASE_TYPE.CHAR);

        private final Class<?> primitiveArrayClass;
        private final Class<?> wrapperArrayClass;
        private final BASE_TYPE baseType;

        BASE_TYPE_ARRAY(Class<?> primitiveArray, Class<?> wrapperArray, BASE_TYPE b) {
            this.primitiveArrayClass = primitiveArray;
            this.wrapperArrayClass = wrapperArray;
            this.baseType = b;
        }

        public Class<?> getPrimitiveClass() {
            return baseType.getPrimitiveClass();
        }

        public Class<?> getPrimitiveArrayClass() {
            return primitiveArrayClass;
        }

        public Class<?> getWrapperClass() {
            return baseType.getWrapperClass();
        }

        public Class<?> getWrapperArrayClass() {
            return wrapperArrayClass;
        }

        public BASE_TYPE getBaseType() {
            return baseType;
        }
    }

    public static Object nextRandom(Class<?> cls) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        // base case: primitive array or wrapper array
        if (cls.isArray()) {
            for (BASE_TYPE_ARRAY i : BASE_TYPE_ARRAY.values()) {
                if (cls.equals(i.getPrimitiveArrayClass()) || cls.equals(i.getWrapperArrayClass())) {
                    // later: random wrapper of cls if primitive
                    // later: is slightly inefficient because we iterate over BTA.values() than iterate in
                    // randomBase using a switch statement.
                    return randomBaseArray(i);
                }
            }
        }
        // base case: if primitive or wrapper
        else {
            for (BASE_TYPE i : BASE_TYPE.values()) {
                if (cls.equals(i.getPrimitiveClass()) || cls.equals(i.getWrapperClass())) {
                    // later: random wrapper array of cls
                    return randomBase(i);
                }
            }
        }

        Constructor<?> constructor = cls.getConstructors()[0];
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        Object[] parameterValues = new Object[parameterTypes.length];

        for (int i = 0; i < parameterValues.length; i++) {
            // Recursively creates objects/ parameters for constructor
            parameterValues[i] = nextRandom(parameterTypes[i]);
        }

        // ----------------------
        // EXCEPTION THROWN HERE
        // ----------------------
        return constructor.newInstance(parameterValues);
    }

    public static Object randomBase(BASE_TYPE baseType) {
        Random rand = new Random();
        switch (baseType) {
            case BYTE:
                return randomByte();
            case CHAR:
                return randomChar();
            case LONG:
                return rand.nextLong();
            case FLOAT:
                return rand.nextFloat();
            case DOUBLE:
                return rand.nextDouble();
            case SHORT:
                return randomShort();
            case BOOLEAN:
                return rand.nextBoolean();
            case INTEGER:
                return rand.nextInt();
        }
        throw new IllegalArgumentException();
    }

    public static Object[] randomBaseArray(BASE_TYPE_ARRAY baseTypeArray) {
        short srt = (short) (1 + new Random().nextInt(Short.MAX_VALUE));
        Object arr = Array.newInstance(baseTypeArray.getWrapperClass(), srt);

        for (int i = 0; i < Array.getLength(arr); i++) {
            Array.set(arr, i, randomBase(baseTypeArray.getBaseType()));
        }
        return (Object[])arr;
    }

    public static Byte randomByte() {
        byte[] b = new byte[1];
        new Random().nextBytes(b);
        return b[0];
    }

    public static Character randomChar() {
        return (char)(new Random().nextInt(85) + 32);
    }

    public static Short randomShort() {
        return (short) (Short.MIN_VALUE + new Random().nextInt(Short.MAX_VALUE * 2 + 2));
    }

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        // I don't fully know how to use @SuppressWarnings yet, so most of my methods throw these exceptions^
        String str = (String)nextRandom(String.class);
    }
}





Safely importing external libraries during runtime in C#

I am building a program where I intend to provide an API, allowing other developers to build .dll libraries that are placed in a folder which my program can find at runtime and import them. I find the files and load them with Assembly.load(), then find the classes using Assembly.GetExportedTypes() which implement a particular interface.

This code is functioning correctly, but frankly I have some concerns about what developers could be importing, particularly with regard to actions such as running executables from their code, trying to access or delete files on the system outside of the program's folder structure, or potentially even establishing some sort of network connection and passing data forward.

I understand that I must accept some level of risk when allowing this sort of feature, but what can I do to harden the program from malicious activity while still allowing the import of external libraries for extensibility?





java getSuperclass().toString() not running my custom toString() (reflection)

[Hi, guys. I'm learning Java with Cay Horstmann's 'Java SE8 for the Really Impatient'. Studying chapter 4]

I want to call the toString() method of the parent class and add something to it. Unfortunately, the call to the toString() method of the parent class seems not to be working.

So far I've got these classes:

public class Point {
    private double _x = 0;
    private double _y = 0;

    public Point(double x, double y) {
        _x=x;
        _y=y;
    }

    @Override
    public String toString() {

        String theString = getClass().getSuperclass().toString() + " => " + getClass().getCanonicalName();

        theString += "[";
        int i=0;
        for (Field theField : getClass().getDeclaredFields()) {
            theField.setAccessible(true);
            try {
                if (i>0) theString += ", ";
                theString += theField.getName() + ": " + theField.get(this).toString();
                i++;
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err1");
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err2");
            }
        }
        theString += "]";
        return theString;
    }
    ...        
}

public class LabeledPoint extends Point {
    private String _label = "";

    public LabeledPoint(String label, double x, double y) {
        super(x, y);
        this._label = label;
    }

    ...

}

And I call them with this main method:

public static void main (String[] args) {
    LabeledPoint lp1 = new LabeledPoint("FirstPoint", 10.5, 30);
    System.out.println("The new point is:");
    System.out.println(lp1);
}

So, I was expecting to get something like this:

Point[_x: 10.5, _y:30.0]=>LabeledPoint[_label: FirstPoint]

But instead, I'm getting :

Point=>LabeledPoint[_label: FirstPoint]

That is, the getClass().getSuperclass().toString() is not executing Point.toString(), but it's just printing out the canonical name.

Why is that?





Using reflection, is there a way to load a .NET type with generic parameters without having to append the number of them to the name?

I am working on my own language and for the sake of .NET interop I've been using the Reflection methods to query the .NET types and method signatures.

open System
let asm = Reflection.Assembly.Load("mscorlib")
let dic = asm.GetType("System.Collections.Generic.Dictionary`2")

The above is how I would load the type of Dictionary directly from mscorlib. Note that unlike in standard code, the 2 at the end separated by the grave character is necessary.

Since C# and F# do not require specifying the number of generic parameters as a part of the name, I've been wondering whether there is a better way of doing this?

This is awkward because right now, I have to write out the full name in my language's code as well.





vendredi 21 juillet 2017

Finding annotated methods in application code from maven integration test

I have a custom annotation in my program that I apply to methods. I would like to find all methods with a particular annotation. From my application code, I can use the Reflections package to do so:

new Reflections(
    new ConfigurationBuilder().setUrls(
        ClasspathHelper.forPackage("com.my.package")
    ).setScanners(new MethodAnnotationsScanner())
    ).getMethodsAnnotatedWith(MyAnnotation.class);

However, when I try to do the same from an integration test invoked via failsafe, no methods are found. How can I get my annotated methods from an integration test?





Int Type vs scala.Int Type

I'm using scala reflections to get all fields of a case class that are not methods. I then want to see if the type is a primitive type or string (or an option of these things). Here's a simple working example that checks if a field is a String.

scala> case class SimpleCase(val1: String)
defined class SimpleCase

scala> val members = typeOf[SimpleCase].members.filter(!_.isMethod).toList
members: List[reflect.runtime.universe.Symbol] = List(value val1)

scala> members.head.typeSignature
res57: reflect.runtime.universe.Type = String

scala> members.head.typeSignature == typeOf[String]
res58: Boolean = true

Works exactly the way that I would expect it to. Here's where things get weird - when I do the same thing with an Int, or any primitive type for that matter, the type checking test fails. Here's an example of said failure:

scala> case class SimpleCase(val1: Int)
defined class SimpleCase

scala> val members = typeOf[SimpleCase].members.filter(!_.isMethod).toList
members: List[reflect.runtime.universe.Symbol] = List(value val1)

scala> members.head.typeSignature
res59: reflect.runtime.universe.Type = scala.Int

scala> members.head.typeSignature == typeOf[Int]
res60: Boolean = false

scala> members.head.typeSignature == typeOf[scala.Int]
res61: Boolean = false

Also, typeOf[Int] prints out

scala> typeOf[Int]
res62: reflect.runtime.universe.Type = Int

The type signature of SimpleCase's val1 states that it is a scala.Int rather than typeOf[Int]'s type signature, which is Int. So I tried comparing val1 to both typeOf[Int] and typeOf[scala.Int] (even though I'm pretty sure they're the same thing) to no avail.

What's going on here? Is there a way around this?





How to convert an Object by the type name and pass it as an argument to another method

here is my code:

using System.Reflection;
Public class ClassA
{
    public ClassA()
    {
        ClassB classB = new ClassB();
        classB.UsingType = "ClassD";
        ClassB.Do();
    }
}
Public class ClassB
{
    public string UsingType { get; set; }
    public void Do()
    {
        ClassC classC = new ClassC();
        Type type = Type.GetType(UsingType);
        Object obj = Activator.CreateInstance(type);
        classC.Do(obj); // Error : cannot convert from 'object' to 'ClassD'
    }
}
public class ClassC
{
    public void Do(ClassD classD) // If I change "ClassD" to "Object" It works!!
    {
        //Do something with classD
    }
}

I get this error: "cannot convert from 'object' to 'ClassD'."

If I change "Do" method argument of "ClassC" from "ClassD" to "Object" the error goes away and then I can cast it to "ClassD" and use that parameter. But that's not what I want.

Is there a way to cast "obj" by "UsingType" string to "ClassD" (in "Do" method of "ClassB") and get rid of the compile time error?

In other words: (since "ClassA" knows the type name string and passes it to "ClassB") how can I cast from "Object" to the type that "ClassC" asks for?





OOP Pattern - using abstract with reflection a lot. Is this a bad pattern I'm falling into?

Lately I've been using this sort of pattern a lot:

abstract class myBaseClass
{
    //some common methods/properties/etc that all inheritors would share
    //some abstract methods/properties/etc that inheritors must implement

    protected abstract bool DoIHandleThisSortOfRequest(...);

    public static myBaseClass GetHandler()
    {
        // some reflection to enumerate through classes
        // that inherit from myBaseClass, and use
        // something like DoIHandleThisSortOfRequest() on each
    }
}

... and, I mean, the code is nice and neat... but it does mean I'm using reflection quite a bit.

For example, I'm currently working on a new process that works via command line than needs to handle a lot of different request types, and found myself using this sort of pattern, kinda like this:

abstract class FunctionRequest
{
    protected abstract string RequestName { get; }
    public abstract void Run();
    public static FunctionRequest GetHandler(string requestName)
    {
        // use reflection to get list of classes deriving from FunctionRequest
        // find one that has instance.RequestName equals requestName
    }
}
public class QueryRequest : FunctionRequest
{
    protected override string RequestName { get { return "Query"; } }
    public override void Run()
    {
        // ... code ...
    }
}

Is there a better way to structure this? I'm not too worried about the overhead of Reflection on this... but I realize if there's a better way to do it, I should get in the habit of doing it the right way :-)