lundi 2 juillet 2018

How to check whether a type is an enum in Kotlin?

At runtime, I am trying to verify whether a particular KClass<out Any> is an enum type or not.

What is the best way to do so? Can this be done without relying on a particular runtime (e.g., JVM or JS)?

fun isEnum( type: KClass<out Any> ): Boolean
{
    ... ?
}





Overriding an internal get-only property from a base class

I have this class, defined in one of .NET's framework assemblies:

public class ExternalClass
{    
   internal double DesiredProperty => 1.0;    
}

I derive from ExternalClass and would like to either override or somehow intercept calls to that property. I'm aware that this can get very hacky, but it's really only for a proof-of-concept.

I tried the straightforward way with reflection, but haven't had any luck:

 private void DoEvilStuff()
    {
        var prop = typeof(ExternalClass).GetProperty("DesiredProperty", BindingFlags.Instance | BindingFlags.NonPublic);

        // Exception: Property has no setter
        prop.SetValue(this, 5);
    }

From another answer:

private void DoEvilStuff()
{
    var prop = typeof(ExternalClass).GetField("<DesiredProperty>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);

    // fails, prop is null:
    prop.SetValue(this, 5);
}

Is there a way to do this with reflection, or any other method with reasonable small effort? I can (properly) work around this for my actual problem, so a "No" is really an acceptable answer, but I'm curious if this would be possible.





Java - how to analyze a function code

We are working with mvc design pattern, where all the data is stored under map.

I want to iterate over all the classes in the system and for each to check what the method is putting on the map and what does the method get from the map.

For example for the next code:

private void myFunc()
{
Object obj = model.get("mykey");
Object obj2 = model.get("mykey2");
.....
model.put("mykey3", "aaa");
}

I want to know that in this function we have 2 gets: mykey and mykey2 and 1 put: mykey3

How can I do it with the code.

Thanks.





dimanche 1 juillet 2018

How to convert annotation into custom object in java

I'm seeing how to get custom annnotation class object from AccessibleObject in java like this.

AccessibleObject m = ...
Named n = m.getAnnotation(Named.class);

But, I don't know, given an java.lang.annotation.Annotation annotation how to convert this into custom class object.

Does java provides any similar utility to do casting?





In a Ruby module, how do you test if a method exists in the context which use the module

Some context

I'm playing with Ruby to deepen my knowledge and have fun while at the same time improving my knowledge of Esperanto with a just starting toy project called Ĝue. Basically, the aim is to use Ruby facilities to implement a DSL that matches Esperanto traits that I think interesting in the context of a programming language.

The actual problem

So a first trait I would like to implement is inflection of verbs, using infinitive in method declaration (ending with -i), and jussive (ending with -u) for call to the method.

A first working basic implementation is like that:

module Ĝue
  def method_missing(igo, *args, &block)
    case igo
    when /u$/
      celo = igo.to_s.sub(/u$/, 'i').to_s
      send(celo)
    else
      super
    end
  end
end

And it works. Now the next step is to make it more resilient, because there is no guaranty that celo will exists when the module try to call it. That is, the module should implement the respond_to? method. Thus the question, how do the module know if the context where module was required include the corresponding infinitive method? Even after adding extend self at the beginning of the module, inside of the module methods.include? :testi still return false when tested with the following code, although the testu call works perfectly:

#!/usr/bin/env ruby

require './teke/ĝue.rb'
include Ĝue
def testi; puts 'testo!' ;end
testu

Note that the test is run directly into the main scope. I don't know if this makes any difference with using a dedicated class scope, I would guess that know, as to the of my knowledge everything is an object in Ruby.





Type check fails for memberProperty returnType superclass

I've got an instance of an object, which I scan for memberProperties that have a proper annotation attached on them. Then, I want to filter based on their return type. For example if declaration is as follows: class AutoValidatedThing : AutoValidatedUserInputComponent {...} and the target instance contains a @ValidComponent val someProperty: AutoValidatedThing = ..., I'd want to get the someProperty as a AutoValidatedUserInputComponent to the end of the following code block:

    val invalidOnes = this::class.memberProperties
        .filter { it.javaField != null && it.javaField!!.isAnnotationPresent(ValidComponent::class.java) }
        .filter { val annotations = it.javaField?.annotations; annotations != null
                && annotations.map { ann -> ann.annotationClass }.contains(ValidComponent::class)
                && it.returnType is AutoValidatedUserInputComponent }
        .map { it.getter.call() as AutoValidatedUserInputComponent }

But it.returnType is AutoValidatedUserInputComponent ALWAYS returns false.

AutoValidatedUserInputComponent is a simple interface:

interface AutoValidatedUserInputComponent {
    fun blabla() : SomeType
}





Set item from sources class like zero item of list in dest class with Dozer

I have sources classes:

  @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private String name;
        private int age;
        private Test test;
    }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  public class Test {
      private String hz1;
      private String hz2;
  }

And I have dest classes:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDest {
    private String name;
    private int age;
    private List<TestDest> tests;
}

Data
@NoArgsConstructor
@AllArgsConstructor
public class TestDest {
    private String hz1;
    private String hz2;
}

I create User and try map it to UserDest:

    DozerBeanMapper mapper = new DozerBeanMapper();
    User user = new User("Bill", 27, new Test("p1", "p2"));
    UserDest userDest = mapper.map(user, UserDest.class);
    System.out.println(userDest);

Output: UserDest(name=Bill, age=27, tests=null)

I add Mapping:

mapper.addMapping(new BeanMappingBuilder() {
            @Override
            protected void configure() {
                TypeMappingBuilder mapping = mapping(User.class, UserDest.class);
                mapping.fields(field("test.hz1"), field("tests[0].hz1"));
                mapping.fields(field("test.hz2"), field("tests[0].hz2"));
            }
        });

And after that output:

UserDest(name=Bill, age=27, tests=[TestDest(hz1=p1, hz2=p2)])

But I need set each field like this

User test.hz1 set to UserDest tests[0].hz1

I want next:

mapping.fields(field("test"), field("tests[0]"));

But this after that I get this output:

UserDest(name=Bill, age=27, tests=[[]])

How can I set one item from sources class to zero item of list in dest class? Maby some converter or somthing else?