samedi 30 juin 2018

Kotlin filter memberProperties by present annotation class

I've got an extension method running on Any type. On that extension method (where this refers to the target instance), I'm trying to filter the memberProperties based on annotation presence.

this::class.memberProperties
        .filter{ it.annotations.map { ann -> ann.annotationClass }.contains(ValidComponent::class)}

But it.annotations is always of size 0

Example of variable declaration on the instance: @ValidComponent var x: SomeType = constructorParam.something or @ValidComponent lateinit var x: SomeType





Restore a struct that satisfy a defined interface from JSON string

I am implementing a task poller (restore unfinished task from a database).

The task must satisfy a defined Task interface:

type Task interface {
    // Identifier returns a unique string of a task
    Identifier() string
    // Data should be persistent
    Data() interface{}
    // Execute a task
    Execute()
}

The data stored in database satisfy the following struct:

type Record struct {
    Identifier string      `json:"identifier"`
    Data       interface{} `json:"data"`
}

When task poller starts, it read the stored data from the database, then (let's just ignore error handling for now):

r := &Record{}
result := database.Get(key)
json.Unmarshal([]byte(result), r)

we restored the saved data from the database into r.

A problem appears that I cannot call the Execute() method because r.Data is actually type of interface{} (map[string]interface{} more specifically ) other than type of Task.

How can I convert or transform the r.Data to become a struct that satisfies Task interface so that I can successfully call Execute() method?





vendredi 29 juin 2018

Can not set int field to java.lang.Integer

I've seached for a solution but what I found was using Hybernate, but i'm trying to do it myself, because i can't use hybernate on class yet.

I try to set the int value I get from ResultSet by using

Field.set(Object value, Object obj)

but it doesn't seem to be working, here's my code:

public class GenericDao<T> {

public static void main(String[] args) {

    //Create instance of GenericDao
    GenericDao<Produtos> dao = new GenericDao<>();

    //select Products (Produtos) from Database
    ArrayList<Produtos> produtos = dao.select(Produtos.class, "");

    //Print all product names
    for (Produtos produto : produtos) {

        System.out.println(produto.getNomeProduto());

    }

}

//Insert creator method
public int insert(Object obj) {
    //Insert is working properly
}


//Select creation method
public ArrayList<T> select(Class<T> c, String whereStatement) {

    //Select statement creation, I know that the String whereStatement
    //is terrible here, i just need to get it working and i'll change it later
    String sql = "SELECT * FROM " + c.getSimpleName() + whereStatement;

    //getting connection
    Connection conexao = new ConnectionFactory("FastFood").obterConexao();

    //Creating ArrayList to return
    ArrayList<T> list = new ArrayList<T>();

    try {

        Statement pstmt = conexao.createStatement();

        ResultSet rs = pstmt.executeQuery(sql);

        while (rs.next()) {

            for (Field f : c.getDeclaredFields()) {

                T obje = c.newInstance();

                boolean wasAccesible = f.isAccessible();
                if (!wasAccesible) {
                    f.setAccessible(true);
                }

                String type = f.getType().getSimpleName();

                if (type.equalsIgnoreCase("String")) {
                    f.set(rs.getString(f.getName()), obje);
                } else if (type.equalsIgnoreCase("int")) {

                    int value = rs.getInt(f.getName());  

                    f.set(value, obje);  //THE ERROR IS HAPPENING HERE, you can ignore the rest if you want to

                } else if (type.equalsIgnoreCase("localdatetime")) {
                    f.set(LocalDateTimeConverter.DateToLocalDateTime(rs.getDate(f.getName())), obje);
                } else if (type.equalsIgnoreCase("double")) {
                    f.set(rs.getDouble(f.getName()), obje);
                } else if (type.equalsIgnoreCase("boolean")) {
                    f.set(rs.getBoolean(f.getName()), obje);
                }

                if (!wasAccesible) {
                    f.setAccessible(false);
                }

                list.add(obje);
            }
        }
    } catch (Exception e) {
        System.err.println("Erro : " + e.getMessage());
    }
    return list;
}

The error I'm getting is: Can not set int field br.com.gtff.bean.Produtos.idProduto to java.lang.Integer

Here is what being used from the Produtos Class

public class Produtos {

private int idProduto;
private String nomeProduto;
private Double valorProduto;
private int gramasProduto;
private Boolean ativo;

}





How in Runtime change annotation properties in Custom BeanPostProcessor

ENVIRONMENT:

Java 8
Srping Framework 5

SITUATION: I need to change in Runtime @GetMapping annotation attributes values.

TASK: I have my controller and durring runtime I need to change value attribute from value = {"/**"} to value = {"/method1", "/method2"}

@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping(value = {"/**"}, produces = {"application/json", "text/csv"})
public ResponseEntity<?> query(HttpServletRequest request, @RequestParam Map<String, String> params) {
    ..........
}

ACTION: I added custom bean post processor and via reflection tried to change the value field of @GetMappg annotation.

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof MyController) {
        Method[] methods = bean.getClass().getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            GetMapping currentAnnotation = AnnotationUtils.findAnnotation(methods[i], GetMapping.class);
            if (Objects.nonNull(currentAnnotation)) {
                LOGGER.debug("GetMapping annotation before:" + currentAnnotation);
                try {
                Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(currentAnnotation);
                annotationAttributes.put("value", new String [] {"/method1", "/method2"});

                    AnnotationAttributes attributes = new AnnotationAttributes(annotationAttributes);
                    AnnotationUtils.postProcessAnnotationAttributes(currentAnnotation, attributes, true);

                    LOGGER.debug("GetMapping annotation after:" + currentAnnotation);
                } catch (Exception e) {
                    LOGGER.error("" + e);
                }
            }
        }
    }

QUESTION: I want to see my changes for value attribute in my current annotation.

ADDITIONAL INFORMATION: As a example for Field we can call

ReflectionUtils.setField(Field field, Object target, Object value);

and will saw our changes for that field.





NoClassDefFoundError loading class with URLClassLoader

We are trying to support plugins for our product and I am using reflection to load a class from a jar.

I create a URL ClassLoader and add all the dependency jars as URLs.

I use that ClassLaoder to load the primary class of the plugin.

I get an instance of the class and a Method reference (a run() method).

When I invoke the method I get this exception:

java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil

This class is in log4j-api-2.10.0.jar, which is included in the classpath of the ClassLoader.

I can see the URL in the classloader in debug so I know its properly referenced.

Sometimes I get a different error, saying that it can't initialize one of my classes but that class is nothing special, no statics or anything.

The primary class that's being loaded by reflection is calling a second class that uses Log4j 2.

When the primary class run() method tries to instantiate the 2nd class that's where this problem occurs.

There is nothing static in either class other than the Logger.

In the debugger I can see from the Method ref that the class was indeed loaded with the URL ClassLoader we created.

This code has been working for a decade and the only thing we've changed is the upgrade to Log4j 2 in the plugin. The class doing the reflective plugin load is just a normal class in the classpath of the application.

Any help would be greatly appreciated.





How to get all subclasses of an abstract base class in Python

Let's say you have an abstract base class with multiple subclasses as follows:

from abc import ABC, abstractmethod

class Parent(ABC):
    @abstractmethod
    def important_func(self):
        pass

class Child1(Parent):
    def important_func(self):
        # Define implementation here
        return

class Child2(Parent):
    def important_func(self):
        # Define implementation here
        return

What I would like to be able to do is either add a static method to Parent or just add a function in the module that will allow me to access all of Parent's subclasses with either an iterator or by returning a container of them.

Something like:

instantiated_subclass_list = [cls() for cls in Parent.__subclasses__()]

This method of finding subclasses looked promising:

How to find all the subclasses of a class given its name?

however, I am not sure if the case still holds when the parent class is an abstract base class and since there isn't any detail on the __subclasses__ method in the docs I feel like there is probably a better (possibly more "pythonic") way to accomplish this.





Invoking method by reflection returns inconsistent results if the class is compiled more than once during run time

I compile a class during runtime and then later call that classes methods. If the class was compiled more than once the boolean methods always return true instead of the response appropriate to the arguments.

The weird part is that when I debug, I can see that the compiled class is the same and correct, the correct method at the correct class path is found and the arguments are the same.

Method that compiles the code:

public static void compile(String conditionClass){
    try {
        String fullPath =  getClassPath() + "/" + target;

        File file = new File(fullPath + ".java");
        if (file.exists())
            file.delete();
        file.createNewFile();

        PrintWriter pw = new PrintWriter(file);
        pw.print(conditionClass);
        pw.flush();
        pw.close();

        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        String[] methodArgs = {fullPath + ".java"};
        javac.run(null, null, null, methodArgs);

        targetClass = Class.forName(target);

        file.delete();
    } catch (Exception e){
        e.printStackTrace();
    }

}

public static String getClassPath() throws Exception {
    for (String s : System.getProperty("java.class.path").split(":"))
        if (s.indexOf("/target/classes") + "/target/classes".length() == s.length())
            return s;
}

Method that calls the code:

public boolean call(String methodName, String[][][] arg1, String[] arg2){
    try {
        Method m = targetClass.getMethod(methodName, new Class[]{String[][][].class, String[].class});
        Object[] args = new Object[]{arg1, arg2};
        Object response = m.invoke(null, args);
        return (boolean)response;
    } catch (Exception e){
        e.printStackTrace();
    }

    return true;
}





DataGridView Scroll show columns over others

I have a datagridview, and when i use scrollbar the columns shown over the others, like this image: here

i have tried DoubleBuffered like that:

1- i created a module named "DoubleBuffer.vb"

2- i add that code in it:

Imports System
Imports System.Reflection
Imports System.Windows.Forms
Module DoubleBuffer
    Public Sub DoubleBuffered(ByVal dgv As DataGridView, ByVal setting As Boolean)
        Dim dgvType As Type = dgv.[GetType]()
        Dim pi As PropertyInfo = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance Or BindingFlags.NonPublic)
        pi.SetValue(dgv, setting, Nothing)
    End Sub
End Module

3- i call that module in Load Event:

DoubleBuffer.DoubleBuffered(DataGridView1, True)

but it give me BLACK Cells

so, what is the problem i faced here?





jeudi 28 juin 2018

filter database columns by reflection with lambda expressions in c#

I am using datatable with individual filtering(each column contains a search box in the table header). I want to use lambda expression to filter the datatable but using the reflection way.I have the column name of the datatabase as a string, and the search value too.I may send one or more column names with their values( send the column name as general parameter with the search value, and the method should know how to classify the column name by reflection method):

 Expression<Func<DatatabseView, bool>> filter = x => x.ColumnName.Contains(SearchValue);

And this is my repository method:

    /// <summary>
    /// Get set of object depends on condition, ordereds by order expression, with pageing and joined with include properties.
    /// </summary>
    /// <param name="filter">Condition to be filter data store by.</param>
    /// <param name="orderBy">Order by Expression.</param>
    /// <param name="pageNum">Page number to used at pageing.</param>
    /// <param name="pageSize">Page size to used at pageing.</param>
    /// <param name="disableTracking">disable tracking</param>
    /// <param name="includeProperties">including related entities</param>
    /// <returns>Ienumerable entities</returns>
    public async Task<IEnumerable<T>> Get(Expression<Func<T, bool>> filter = null,
        Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
        int? pageNum = null,
        int? pageSize = null,
        bool disableTracking = true,
        Func<IQueryable<T>, IIncludableQueryable<T, object>> includeProperties = null)
    {
        IQueryable<T> query = DbSet;
        if (disableTracking)
            query = query.AsNoTracking();
        if (includeProperties != null)
            query = includeProperties(query);
        if (filter != null)
            query = query.Where(filter);
        if (orderBy != null)
            query = orderBy(query);
        if (pageNum != null && pageSize != null)
            query = query.Skip(pageNum.Value ).Take(pageSize.Value);
        return await query.ToListAsync();
    }

How to do this kind of search using lambda expressions with reflection?





Inspect function signature in Lua 5.1

In this answer, a method is provided for inspecting the signature of a Lua function. The answer notes that:

This algorithm works with Lua 5.2. Older versions would be similar but not the same:

What would the equivalent be in Lua 5.1?





Get Properties of Dynamic Object

I tried using reflection as suggested as the answer here, but nothing is returned. Here's my code:

for (int x = ro.records.Count - 1; x >= 0; x--)
{
    dynamic foundObject;
    if (outputList.TryGetValue(ro.records[x].Id, out foundObject))
    {
        string s = ro.records[x].Id; //THIS CONTAINS A VALUE
        PropertyInfo[] props = ((object)ro.records[x]).GetType().GetProperties(); //THIS FINDS 0 PROPERTIES
        foreach(PropertyInfo pi in props)
        {
            //Do stuff
        }
    }
}

As my comments in the code state, I can get the "Id" property, but my PropertyInfo[] array is always empty. I'm stumped.





Why getAnnotatedParameterTypes does not see annotations for array argument?

For some reason I don't understand why this code prints true and false, what is special about array that it does not include that annotation here?
It works as expected if you use getParameters instead.

public static void a(@Lel String args) {}
public static void b(@Lel String[] args) {}
public static void main(String[] args) throws Exception {
    System.out.println(Test.class.getDeclaredMethod("a", String.class).getAnnotatedParameterTypes()[0].isAnnotationPresent(Lel.class));
    System.out.println(Test.class.getDeclaredMethod("b", String[].class).getAnnotatedParameterTypes()[0].isAnnotationPresent(Lel.class));
}





Veracode - How to Fix CWE-470: Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')

I got a 470 on a line in my code and rightfully so as defined by Vera.

Vera says to fix: Apply strict input validation by using whitelists or indirect selection to ensure that the user is only selecting allowable classes or code.

So I created a strict whitelist of what class name reflection can have access to as a Set

I then wrapped the Class.forName in an if (whitelist.contains(className) { Veracode still fires in here with a 470 }

Anyone know what the fix has to look like for Vera not to fire? I feel I have followed their recommended remediation.





java class.getAnnotation(Class?> class) returns null

I have written an annotation:

@Documented
@Retention(RUNTIME)
@Target(TYPE)
/**
 * @author christian
 *
 */
public @interface HeraklesObject {

}

I use it in an osgi environment (eclipse oxygen with tycho) in a bundle. In another bundle (a test fragment to be specific) i check classes from the first bundle for this annotation, using:

class.getAnnotation(HeraklesObject.class)

I am sure, that the queried class has this annotation, but I get always null result.

The retention policy seems right to me, but I am not sure if a class loader issue is present and I don't know how I check this. Or do you see another cause? Thanks Christian





mercredi 27 juin 2018

Using golang reflect, can I do type declaration dynamically?

package main

import (
    "fmt"
    "reflect"
)

type Config struct {
    Name string
    Age  int
}

func main() {
    a := make(map[string]Config)
    a["m"] = Config{"mingukang", 29}
    t := reflect.TypeOf(a["m"])
    v := reflect.New(t)
    c := v.Interface().(*Config)
    fmt.Println(c)

}

In c := v.Interface().(*Config), I want to replace *Config to variable contains Type value like a:= *Config and declare it like, c := v.Interface().(a)

Is it possible in golang?





log4j log file not rolling while setting filepath on runtime

Code 2 is injecting Logger instance into LOG field in Code 1. The logs are going to the correct file but the logs are not rolling. However, when using Code 1 with Code 3, logs are rolling. What I need is for Code 1 to work with Code 2. The core logic for appending the RollingFileAppender is the same but I am out of ideas why the log won't roll in the first case. Will you please explain what I am doing wrong and what could be a possible solution.

@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface Log {
    Class<?> clazz();
}

Code 1:-

@RestController
@RequestMapping(value = "/util/")
public class UtilityController {
    @Log(clazz = COScheduler.class)
    private static Logger LOG;
}

Code 2:-

package text.worker.config.log;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;    

@Component
public class LogInjector implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(final Object bean, String name) throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                // make the field accessible if defined private
                ReflectionUtils.makeAccessible(field);
                if (field.getAnnotation(Log.class) != null) {
                    Class<?> cl = ClassUtils.getUserClass(field.getAnnotation(Log.class).clazz());

                    Logger log = Logger.getLogger(cl);

                    if(log.getAppender("worker") == null) {
                        PatternLayout patternLayout = new PatternLayout();
                        patternLayout.setConversionPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c{1}:%L - %m%n");
                        try {
                            RollingFileAppender appender = new RollingFileAppender(patternLayout, "D://aa.log",true);
                            appender.setMaxFileSize("500KB");
                            appender.setMaxBackupIndex(10);
                            appender.setName("worker");
                            appender.activateOptions();
                            log.addAppender(appender);
                        } catch (IOException e) {
                        }
                    }   
                    //log.warn("LogInjector postProcessBeforeInitialization Log getAppender "+field.getAnnotation(Log.class).clazz());                    

                    field.set(bean, log);
                }
            }
        });
        return bean;
    }
}

Code 3:-

if(LOG.getAppender("worker") == null) {
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.setConversionPattern("%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");
            try {
                RollingFileAppender appender = new RollingFileAppender(patternLayout, "D://aa.log",true);
                appender.setMaxFileSize("500KB");
                appender.setMaxBackupIndex(10);             
                appender.setName("worker");
                appender.activateOptions();
                LOG.addAppender(appender);              
            } catch (IOException e) {
            }
        }





Uninitialized TypeScript class properties are not iterated

I have the following class:

export class SomeModel {
  prop1: number;
  prop2: number;
  comment: string;
}

and the following method to dynamically get its properties:

getTypeProperties<T>(obj: T): string[] {
    const ret: string[] = [];
    for (const key in obj) {
      if (obj.hasOwnProperty(key))
        ret.push(key);
    }
    return ret;
}

The following call returns an empty array:

getTypeProperties(new SomeModel());

However, if I explicitly initialize all properties with null, the properties will be returned correctly:

export class SomeModel {
  prop1: number = null;
  prop2: number = null;
  comment: string = null;
}

Question: Is this normal behavior? Or is there a TypeScript compiler switch to toggle this?

I do not know if it is relevant, but here is the tsconfig.json content:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}





mardi 26 juin 2018

Removing a pointer from reflect.Type

I have a reflect.Type that contains a double-pointer to a struct. I'd like to be able to remove one level of indirection to have a pointer to the struct. Is this possible? For example, I'd like to do this:

func foo(x interface{}) {
    typ := reflect.TypeOf(x)
    fmt.Printf("%v", typ) // prints **Foo
    realType := typ.PointsTo()
    fmt.Printf("%v", typ) // prints *Foo
}

But as far as I can see, this functionality does not exist. There is an Indirect function that operates on Values, but I can't see anything similar that works on Types.





TargetParameterCountException when mocking function to return its input

I have a function that requires mocking out to return one of its parameters.

The function looks as follows:

 IEnumerable<XDocument> WrapDocuments(MessageSettings messageSettings,
        IEnumerable<XDocument> documents);

I am mocking it like this:

 mockDocumentWrapper
      .Setup(m => m.WrapDocuments(It.IsAny<MessageSettings>(), It.IsAny<IEnumerable<XDocument>>()))
      .Returns((IEnumerable<XDocument> x) => x);

When the test which invokes WrapDocuments() runs, I get a TargetParameterCountException. What am I doing wrong here?





lundi 25 juin 2018

How to reflectively parameterise a generic type in Scala?

How can I implement the following psuedocode in Scala using reflection?

trait Foo[A]

def parameterizeFoo(param: Class[_]): Class[_] = ???

assert(parameterizeFoo(classOf[Int]) === classOf[Foo[Int]])

Note: I do not have access to the type of A at compile time, hence the _. The entire solution needs to be performed reflectively (e.g. I cannot have parameterizeFoo[A : ClassTag](...)).





dimanche 24 juin 2018

When to await a dynamically invoked method?

My code does this to invoke a registered method when a network requests comes in. It's part of an RPC system.

Delegate method;
object result = method.DynamicInvoke(args);

When the method returns a value, everything is good. But when it returns something awaitable, I'm not interested in trying to give that awaitable something back to the network caller. They won't make any use of it, and it's probably not transferrable anyway. Instead I need to wait for it and then return the actual result.

I could just check if the method's return type is something like a Task. Or a Task<T>. Is that enough? Can't there be other awaitable things in the universe? How would I test for the type Task? I mean I can't just do something like this:

method.Method.ReturnType is Task

It won't be true. And there's also no:

method.Method.ReturnType.IsAwaitable

I acknowledge that I won't be able to wait for an async void method. But anything else, eventually awaitable, should be awaited.





Get calling method using StackTrace

I have two scenarios where I want to know which is the caller method of some method I´m executing.

These are the scenarios:

1)

public static void ExecuteMethod(object obj)
{
    var mth = new StackTrace().GetFrame(1).GetMethod();
    string methodName = mth.Name;
}

And I call it this way:

public class Process
{
    public int Handle { get; set; }
    public string Name { get; set; }
    public int ProcessID { get; set; }

    public dynamic GetOwner()
    {
        return WMIMethod.ExecuteMethod(this);
    }
}

When this is executed the result of methodName is the one I expect: GetOwner

The second and problematic scenario is this one:

2)

public static dynamic ExecuteMethod(object obj, dynamic parameters)
{
    var mth = new StackTrace().GetFrame(1).GetMethod();
    string methodName = mth.Name;
}

And I call it this way:

public class Process
{
    public int Handle { get; set; }
    public string Name { get; set; }
    public int ProcessID { get; set; }

    public dynamic GetOwner(dynamic inParams)
    {
        return WMIMethod.ExecuteMethod(this, inParams);
    }
}

In this scenario, when I call new Process().GetOwner(new { MyParam = "Something" } ) the result of methodName isn´t anymore what I would expect to be (GetOwner) and instead of that methodName is CallSite.Target and the result of mth is

{Void CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Type, ORMi.Sample.Models.Printer, System.Object)}

Anyone knows why is the second case different of the first one??. How can this be solved???.

Thanks!.





Android reflection can't find constructor

I have that class:

public class DNDRunner {
    private NotificationManager mNoMan;

    public DNDRunner(Context context) {
        mNoMan = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public void run(String param) {
        mNoMan.setZenMode(Integer.parseInt(param), null, "DNDRunner");
    }
}

And i call run method by reflection using:

try {
    Class mRunner = Class.forName(runner);
    Constructor constructor = mRunner.getConstructor(new Class[]{Context.class});
    Object object = constructor.newInstance(new Object[]{mContext});
    Method run = mRunner.getMethod("run", new Class[]{String.class});
    run.invoke(object, new Object[]{value});
} catch (Exception e) {
    Log.e(TAG, "Runner", e);
}

but i get:

java.lang.NoSuchMethodException: <init> [class android.content.Context]
at java.lang.Class.getConstructor0(Class.java:2320)
at java.lang.Class.getConstructor(Class.java:1725)

what i'm doing wrong? the constructor is obviously there





how to clone object model swift

I want using Mirror to add to the parent class without having to add a clone of the child's class

Do you think this is possible?

base class :

class BaseModel {

 func clone() -> BaseModel {

          let mirror = Mirror(reflection : self)
           for (lable , value) in mirror.children {

             }
          return ...
   }
}

subclass :

class UserModel:BaseModel {

   var name:String!
   var family:String!

}

use sample :

 let cloneModel = self.userModel.clone()





Get generic type of class at runtime is not working

I have two classes and one interface

public class ExcelReader<T> extends Reader<T> implements RowColumnReader<T> {

    // private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) {};
    // private final Type type = typeToken.getType(); 
    /* public Type getType() {
        return type;
        }*/
    // Useing Guava getting System.out.println(reader.getType()) T as ouput

        @Override
        public List<T> readFile(String file) {
          //my code
        }
    }
public abstract class Reader<T> {
    protected Class<T> clazz;

    /*public Reader() {
        clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }*/
    // Constructor is commented beacuse getting Exception java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
}

public interface RowColumnReader<T> extends HeaderFields<T>{

    public List<T> readFile(String file);
}

public interface HeaderFields<T> {

    default List<String> getHeader(Class<T> clazz) throws HeaderNotDefiendException {
        //my code
        return headerList;
    }

}

I have tried all possible way to get class of generic type. I followed Get generic type of class at runtime and even tried all solution given in that page. But still not getting any luck.

Even with Gauva

https://stackoverflow.com/a/19775924/2290078 getting the output of getType() is T not the actual generic class

My test code is

Reader<Test> reader = new ExcelReader<>();
//System.out.println(reader.getType());  ---> output is T 
List<Test> list = reader.readFile("Sample.xlsx");
System.out.println(list);





samedi 23 juin 2018

Read all methods on an interface and list their names [duplicate]

This question already has an answer here:

I have a package:

package fruit
import "fmt"

type Fruit struct {}

func (f Fruit) Banana(count int) string {
     return fmt.Sprintf("%d bananas")
}

func (f Fruit) Melon(count int) string {
     return fmt.Sprintf("%d melons")
}

And I want to use reflection to process all the methods on the Fruit type and print out "Banana" and "Melon". I'm having trouble getting the method names. Here's what I have so far:

package main
import (
       "fmt"
        "reflect"
        "runtime"
)

r := reflect.ValueOf(Fruit{})

for i := 0; i < r.NumMethod(); i++ {
     method := r.Method(i)
     methodName := runtime.FuncForPC(method.Pointer()).Name()
     fmt.Println(methodName)
}

Unfortunately, when I run it, I just get the name of some inner mechanism of reflection:

reflect.methodValueCall

reflect.methodValueCall





vendredi 22 juin 2018

How can I use Scala reflection to get only primary constructor parameters?

I have a case class:

case class Cow(breed: Breed, gender: Gender)(implicit grass: Pasture) {
  val hasSpots: Boolean
}

How can I use reflection at runtime to get back just the list (breed, gender)? Here's what doesn't work:

def getConstructorParams[C](implicit ct: ClassTag[C]) =
  ct.runtimeClass.getDeclaredFields.map(_.getName)
  // returns (breed, gender, grass, hasSpots)

def getConstructorParams[C](implicit ct: ClassTag[C]) =
  ct.runtimeClass.getConstructors.head.getParameters.map(_.getName)
  // returns (arg0, arg1, arg2)

The first solution includes non-constructor fields (hasSpots), which is not what I want. The second solution loses the parameter names. Both methods also include the curried implicit grass/arg2 argument, which I also don't want.

Is there some way to get back just the (breed, gender) fields?





How to use reflection to get all the variables in an object?

I'm currently using this code to get all the variables in an object and place the data in a Dictionary (the key is a variable name, the value is the variable's contents).

foreach (var property in PropertiesOfType<string>(propertiesJSON))
{
    dictionary.Add(property.Key, property.Value);
}

In this code, propertiesJSON is the object I need. Here's the PropertiesOfType method:

public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
    return from p in obj.GetType().GetProperties()
           where p.PropertyType == typeof(T)
           select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}

When I test my Dictionary for any data, there are no values (I used Visual Studio's debugging stuff to check, and my program also printed out all the data inside the Dictionary - which is of course, not there). Please tell me the mistake I'm doing here (I'm still learning to code, I'm 15 at the time of posting this).

Thanks in advance.





Using a string as a name of an attribute of a class in C#

the question probably already has been answered, but i honestly dont know what to search for, an "Reflection" did not solve my issue.

I want to call a field by a string such as:

    string str = "Green";
    Color colorForPurpose = Color.str;

Of course this does not work, but the purpose should be clear.

Anyone has an idea?





Getting static properties using reflection

I created a class:

public class MyClass
{

  public String Id
  {
    get { return "ID"; }
  }

  public String Name
  {
    get { return "NAME"; }
  }

  public static string Static1 = "STATIC1";
  public static string Static2 = "STATIC2";
}

and when I try to get all properties (statics included) I only get the properties Id and Name.

The code to get properties:

typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static)

Should I use another BindingFlags?





Instantiate a Class by Accessing Private Constructor

//Sample class Student.java

 public class Student {
        private Integer sudentId;
        private String studentName;
        private Student(){}
        private Student(Integer studentId, String studentName) {
            this.studentId = studentId;
            this.studentName = studentName;
        }
        public Integer getStudentId() {
            return studentId;
        }
        public String getStudentName() {
            return studentName;
        }
    }

In below code, There are two ways to instantiate the class
1- Find the private constructor using given constructor name and instantiate the class. 2- Find the private constructor for given number of arguments and types and instantiate the class

        import java.lang.reflect.Constructor;
        import java.lang.reflect.InvocationTargetException;
        import java.lang.reflect.Modifier;

        public class PrivateConstructorDemo {
            //Find the private constructor using given constructor name and instantiate the class.
            public void createObjectByConstructorName(int id, String name) throws NoSuchMethodException, SecurityException,
                    InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{

                Constructor<Student> constructor = Student.class.getDeclaredConstructor(Integer.class, String.class);
                if (Modifier.isPrivate(constructor.getModifiers())) {
                    constructor.setAccessible(true);
                    Student student = (Student)constructor.newInstance(id, name);
                    System.out.println("Student Id:"+ student.getStudentId());
                    System.out.println("Student Name:"+ student.getStudentName());
                }
            } 

            //For given number of arguments and types and instantiate the class. 
            public void createObject(int id, String name) throws InstantiationException, 
                                IllegalAccessException, IllegalArgumentException, InvocationTargetException {

                   Constructor<?>[] constructors = Student.class.getDeclaredConstructors();
                   for (Constructor<?> constructor : constructors) {
                     if (Modifier.isPrivate(constructor.getModifiers())) {
                        constructor.setAccessible(true);
                        Class<?>[] clazzs = constructor.getParameterTypes();
                        if (constructor.getParameterCount() == 2 && clazzs[0] == Integer.class && 
                                                             clazzs[1]  == String.class) {
                            Object ob = constructor.newInstance(id, name);
                            if (ob instanceof Student) {
                                Student student = (Student)ob;
                                System.out.println("Student Id:"+ student.getStudentId());
                                System.out.println("Student Name:"+ student.getStudentName());
                            }
                        }
                     }
                   }
            }

            public static void main(String[] args) throws InstantiationException, IllegalAccessException,
                    IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

                PrivateConstructorDemo obj = new PrivateConstructorDemo();
                obj.createObject(10, "Sandeep");
                System.out.println("-------------------------");
                obj.createObjectByConstructorName(20,"Sandeep");
            }
        } 





Is it possible to execute code before a field is accessed in java?

I am trying to automate the construction of some objects in java.

To do this, I have these sample classes:

class TestInjected extends CommonAncestor {

  TestInjected() {
    System.out.println("I am Test Injected");
  }

  void exist() {
    System.out.println("Hey there, I exist");
  }

}

class CommonAncestor {

  CommonAncestor() {
    super();
    init();
  }

  void init() {
    try {
        Field f = this.getClass().getDeclaredField("x");
        f.set(this, f.getType().newInstance());
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {
    } catch (InstantiationException e) {
    }
  }

}

public class TestInjection extends CommonAncestor{
  TestInjected x;
  private TestInjected y;

  private TestInjected getY() {
    if (y == null) {
      y = new TestInjected();
    }
    return y;
  }

  public TestInjection() {
    super();
  }

  public void test() {
    x.exist();
  }

  public void test2() {
    getY().exist();
  }

}

And I also have a testing class:

public class TestInjectionTest {

  @Test
  public void test1() {
    TestInjection t = new TestInjection();
    t.test();
    t.test2();
  }
}

What I am doing here is, on constructor, I check for the Field x, and I initialize it via reflection. This way, I make sure that whenever a method is called, like in this case, test(), Field x has already been initialized, and therefor, it works.

The second approach, is to force programmers to use a getter, in this case, for Field y, where this getter method makes sure to initialize the object.

However, I am wondering, if hava has any way to execute reflection, when a variable is accessed. Let's say, instead of having to execute reflection code on constructor, if somehow, that code could be executed whenever "x" is required.

i.e:

x.exist()

--> check x is getting called, initialize it, and then call exist()

Any reflection method, or any library, that gives me this?





jeudi 21 juin 2018

C++ Reflection for bit field structs

I am looking for a way to do "reflection" in C++ over a bit-field struct like this:

 struct Bits {
    uint32_t opCode : 5;
    uint32_t header : 3;
    uint32_t source : 5;
    uint32_t destination : 5;
    uint32_t offset : 13;
 };

My goal is to be able to get things like:

  1. All member names as std::string list ex. "opCode", "header", etc...
  2. The underlying typename as a std::string ex. "uint32_t"
  3. The number of bits for each field as a std::int list ex. 5,3,5,5,13

with minimal hand-coding, macros, or boilerplate code.

After reading through this StackOverflow post, it is clear there are some "reflection" capabilities provided by libraries outside of standard C++. Looking into things like Precise and Flat Reflection, Ponder, Boost Reflect, and even Boost Hana, I have not found support for something like this.

I have already found a way to get the member names and typenames of a non-bitfield struct using Boost Hana [this achieves #1 and #2 for ordinary structs], and there is a way to get the member names of a bitfield struct using Boost Fusion [this achieves #1 for bitfield structs], though it is messy.

Alternatively, manually flattening/decaying the struct to a single unit32_t member struct like:

struct BitsFlattened{
  uint32_t message;
}

with manually coded getters and setters for the appropriate members is also a possibility, where getters might expose the information by their name ex. getopCode05(), getheader69().





Pass Type argument to Generic Class

I need to pass type as an argument to a generic class. I am trying to get the type from list of types. Example:

List listType;
listType.Add(typeof(x)); //x is the class name
listType.Add(typeof(y)); //y is the class name

listClass.getValues(); //not able to pass argument as generic.





C# get property value from object using custom attribute

I have this POCO class with properties that use a custom attribute:

Application status flags POCO class

public class ApplicationStatusFlags
    {
        public int ApplicationId { get; set; }

        [SectionFlag("APPLICANTPERSONALDETAILS")]
        public bool PersonalDetailsStatus { get; set; }

        [SectionFlag("APPLICANTECREGISTRATION")]
        public bool EcRegistrationStatus { get; set; }

        [SectionFlag("APPLICANTCV")]
        public bool CvUpload { get; set; }

        [SectionFlag("APPLICANTSTATEMENT")]
        public bool IceAttributeStatement { get; set; }

        [SectionFlag("APPLICANTCPD")]
        public bool CpdUpload { get; set; }

        [SectionFlag("APPLICANTORGCHART")]
        public bool OrgChartUpload { get; set; }

        [SectionFlag("APPLICANTSPONSORDETAILS")]
        public bool SponsorDetails { get; set; }
    }

Section flag attribute class

 [AttributeUsage(AttributeTargets.All)]
    public class SectionFlagAttribute : Attribute
    {
        /// <summary>
        /// This constructor takes name of attribute
        /// </summary>
        /// <param name="name"></param>
        public SectionFlagAttribute(string name)
        {
            Name = name;
        }

        public virtual string Name { get; }
    }

I'm trying to get the value of one of these properties by using a string with the section flag name.

So if var foo = "APPLICANTSPONSORDETAILS" I would get the boolean value of SponsorDetails.

Sample code

    updateAppStatusFlag.ApplicationId = applicationId;

    var applicationStatuses =
        await _applicationService
            .UpdateApplicationStatusFlagsAsync<ApplicationStatusFlags>(updateAppStatusFlag);

    var foo = "APPLICANTSPONSORDETAILS";

Any ideas how to do this? I know I can use reflection but I've had problems getting it to work.

Thanks





Casting a reflected object to another type with a GenericTypeArgument during runtime

Situation:

In an api controller I get a string of a type and need to get a working Iqueryable from this.

I can get something from this through reflection on the dbcontext, which has all the objects I would need as DbSet<Type>, which I then do AsQueryable() on.

Problem is that the only way to get the Correct DbSet from the context is through reflection. But this only return an object of type Object.

I don't know any way to cast this object back to it's DbSet<Type> during runtime and I was wondering if someone else knew of it.





mercredi 20 juin 2018

Calling a generic function where the type of the generic function is determined by an input string

I am trying to call a generic function where the type of the generic function is determined by an input string. I want a function that takes in a string, uses reflection to turn that string into a type and then calls a generic function with that type. I have been working with the solution proposed in How do I use reflection to call a generic method? but I just cannot get it to work. Any help would be greatly appreciated.

//This is the generic function(just a simple example function that writes out the incoming type):
public class SelectableRepository
{
    public virtual string GetTypeOfEntity<TEntity>()
    {
        return typeof(TEntity).ToString();
    }
}

//This is the controller that is attempting to call the generic function with the type of "inputString"
public class MyController
{
    public void MyFunction(string inputString)
    {
        //This is how I have been trying to invoke the method but to no avail:
        var myType = Type.GetType("Models.DatabaseModels." + inputString);              //Get the type of the input string
        MethodInfo method = typeof(SelectableRepository).GetMethod("GetTypeOfEntity");  //Get the generic method from SelectableRepository
        MethodInfo genericMethod = method.MakeGenericMethod(myType);                    //Initialize the generic method with the type from the input string
        genericMethod.Invoke(this, null);                                               //Call the method, I'm pretty sure this is wrong
    }
}

//This is an example of a class that could go into the generic method, the inputString would then be "Company"
namespace Models.DatabaseModels
public class Company 
{
    public string Name { get; set; }
}

I put a breakpoint on the genericMethod.Invoke line and looked at the contents of my variables:

myType = {Models.DatabaseModels.Company}
method = {System.String GetTypeOfEntity[TEntity]()}
genericMethod = {System.String GetTypeOfEntity[Company]()} 

I am getting an error on the last line of this code: genericMethod.Invoke(this, null);

The error reads: TargetException: Object does not match target type.

Am I doing something completely wrong?





Using PropertyInfo as key

I am creating app where I need to cache my custom attribute, so I was thinking about best approach and decided to use ConcurrentDictionary as my "cache". My question is if I can use PropertyInfo, or MethodInfo as keys? Are they unique for each method and are they same for each comparison?





Java: instanceof vs class name switch performance

I was interested in performance question about determine type of object and write some benchmarks with 2 ways of determination.

Can someone explain me why variant with instanceof faster 350 times than variant with class name switching with strings?

Code:

class A {}
class B extends A {}

public class InstanceOfBenchmark {
    public static final Object a = new A();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public void testInstanceOf()
    {
        if (a instanceof B) {}
        else if (a instanceof String) {}
        else if (a instanceof ArrayList) {}
        else if (a instanceof HashMap) {}
        else if (a instanceof HashSet) {}
        else if (a instanceof A);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public void testName() {
        String class_name = a.getClass().getSimpleName();

        switch (class_name) {
            case ("B") :
            case ("String") :
            case ("ArrayList") :
            case ("HashMap") :
            case ("HashSet") :
            case ("A") :
        }
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(InstanceOfBenchmark.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(100)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Results:

Benchmark                            Mode  Cnt     Score    Error   Units
InstanceOfBenchmark.testInstanceOf  thrpt  100  3482.001 ± 25.447  ops/us
InstanceOfBenchmark.testName        thrpt  100    10.579 ±  0.078  ops/us

I run tests with 200 times warmup and 2000 iteration too, result was same.





How do I set proxy on WebView now that Chromium is obfuscating class names?

I've been using a solution similar to the answer proposed here to set a WebView proxy. However, it appears that chromium started obfuscating class names, so identifying the broadcast receiver by reflection using the class name is no longer possible with newer chromium versions.

A solution that I thought about is to invoke onReceive on ALL broadcast receivers in the current app-context.

This is not an ideal solution, because it may have unwanted side effects by invoking the wrong receivers.

Is there a better way to do this? Thanks

Building on the previous answer, my solution would look something like this:

    Class applictionCls = Class.forName(applicationClassName);
    Field loadedApkField = applictionCls.getField("mLoadedApk");
    loadedApkField.setAccessible(true);
    Object loadedApk = loadedApkField.get(appContext);
    Class loadedApkCls = Class.forName("android.app.LoadedApk");
    Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
    receiversField.setAccessible(true);
    ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
    ArrayMap contextReceivers = (ArrayMap) receivers.get(appContext);
    for (Object rec : contextReceivers.keySet()) {
        Class clazz = rec.getClass();

        Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
        try {
            onReceiveMethod.invoke(rec, appContext, intent);
        } catch (Exception e) {
            // oops, couldn't invoke this receiver
        }
    }





mardi 19 juin 2018

How to set culture on instances created with reflection

In our LOB-application we implemented a simple plugin-system using reflection. Potential plugin-dlls are scanned for types that implement a certain interface and if found are instantiated using Assembly.CreateInstance(). The instantiated type has a method that returns a FrameworkElement (WPF) for display in the UI.

Our problem: when displayed in the UI, the FrameworkElement will use the default culture for localization.

The apps culture may differ from the OS-culture and is set within the OnStartup()-event of the app, by setting

        CultureInfo info = new CultureInfo(language);
        Thread.CurrentThread.CurrentCulture = info;
        Thread.CurrentThread.CurrentUICulture = info; 

Every directly referenced assembly in the project will happily return correctly localized resources (e.g. error messages from backend or license-service).

How can we apply a specific culture when dynamically loading assemblies/instantiating types using reflection?





Want to convert Excel file to PDF using Spire.Xls but throws a Reflection Exception

Just want to use Spire to get an Excel file and save as PDF:

            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"D:\excels\Report.xlsx", ExcelVersion.Version2016);
            workbook.SaveToFile(@"D:\excels\" + name + ".pdf", Spire.Xls.FileFormat.PDF);

but throws the following exception at the first line:

enter image description here

I have set copy to local to true in all references but still throws the exception.

Any ideas?

Thanks





Why does invoking a method with params object[] as args throw a cast error?

I am trying to wrap my soap-calls with a generic wrapper to simplify logging and other commons.

When trying to invoke a method on the client I send in, I get this error thrown when using parameters:

{"Unable to cast object of type 'System.String' to type 'System.String[]'."}

My code:

private T CallExternalSoap<T>(object client, string funcName, params object[] args)
        {
            var type = client.GetType();

            var method = type.GetMethod(funcName);

            if (method is null)
            {
                throw new NullReferenceException($"Could not find method {funcName} on object of type {type}.");
            }

            if (method.GetParameters().Length != args.Length)
            {
                throw new Exception($"Number of parameters in {args} does not match number of expected parameters in method {funcName} . Expected {method.GetParameters().Length} parameters");
            }

            var result = (T)method.Invoke(client, args);
            return result;
        }

Calling code, which require one parameter(a string):

    object[] myObjArray = { "Sweden" };
    var client = new org.oorsprong.webservices.CountryInfoService();
    var asdads = loggy.CallExternalSoapAndLog<string[]>(client, "CountryISOCode", myObjArray);

No matter which objects/params I send in I get that error. Tried string, objects, almost anything. Any ideas?





Using reflection for inner class

i'm currently using reflection for setting up instances of specified class. I was wondering if it was possible to apply this method to the following kind of class

namespace tmp {
      public class myClass
        {
            public class InnerClass
            {
                public int I { get; set; }
                public int B { get; set; }
            }
            public string Prop1 { get; set; }
            public Test Prop2 { get; set; }
        }
    }
}

So I tried to obtain the properties for the type 'myClass'

            Type type = Type.GetType("tmp.myClass");
            object objInstance = Activator.CreateInstance(type);
            PropertyInfo[] properties = type.GetProperties();
            myClass obj = Activator.CreateInstance(type);

Now , the array 'properties' will have the first element of the type PropertyInfo, that i can use for assigning a value to the instance obj

properties[0].SetValue(obj,"MyString");

But then, i'm not able to do the same thing with the property Prop2, in fact the second element of properties is of the type System.Reflection.RuntimePropertyInfo, so I can't find a way for editing its value.

As now, I tried using the following method

        Type type1 = Type.GetType("tmp.myClass");
        Type type2 = Type.GetType("tmp.myClass.InnerClass");
        var obj = Activator.CreateInstance(type1);
        var obj2 = Activator.CreateInstance(type2);

        PropertyInfo[] properties = type1.GetProperties();
        properties[1].SetValue(obj, obj2);

But when creating the instance of type2 , System.ArgumentNullException gets thrown.

Thank you.





lundi 18 juin 2018

Golang reflect to test if its a string

Whats wrong with my code? Im trying to test if a value coming from GJson library is a string in the quickest and simplest way possible ( I dont want to use a switch type assertion ).

if reflect.TypeOf(gjson.Get(input, "name").Value()) != "string" {
    return "Not a string!"  
}

Thanks!





Log any method call of an instance

Is it possible to log any method call of a class instance? I have the following instance:

InputStream serverInputStream = this.serverProcess.getInputStream();

I would like to see at a given time during runtime what method has been called in serverInputStream. I believe the solution for that is reflection, specifically a proxy. I already tried to make this example work, but yet unable to make it running.

I thought of a code similar to this:

MyInterceptor myInterceptor = new MyInterceptor(this.serverProcess.getInputStream());
InputStream serverInputStream = myInterceptor.getInterceptedInstance();

serverInputStream.methodOne();
serverInputStream.methodTwo();
serverInputStream.methodThree();

myInterceptor.printIntercepts();

Having a result similar to this:

1. InputStream.InputStream();
2. InputStream.methodOne();
3. InputStream.methodTwo();
4. InputStream.methodThree();

Is that possible?





c# FastMember how to check if field name is correct

I need to get field value from class by name. Reflection is slow so i found FastMember what are you think about it?

And my main question: I have this code:

ObjectAccessor accessor = ObjectAccessor.Create(item);
string fieldDbName = dataType.Name.Replace("REFERENCE_ORDER_", "");
object fieldValue = accessor[fieldDbName];

How can I check if fieldDbName exists in accessor?





Android check if notifications are enabled for specific package

I'm developing a system application and I need to check from my application if a certain package has notifications enabled or not.

I've been triying this code:

public static boolean isNotificationEnabled(Context context) {

    AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

    ApplicationInfo appInfo = context.getApplicationInfo();

    String pkg = context.getApplicationContext().getPackageName();

    int uid = appInfo.uid;

    Class appOpsClass = null; /* Context.APP_OPS_MANAGER */

    try {

        appOpsClass = Class.forName(AppOpsManager.class.getName());

        Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);

        Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
        int value = (int)opPostNotificationValue.get(Integer.class);

        return ((int)checkOpNoThrowMethod.invoke(mAppOps,value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

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

    return false;
}

The issue is that it is returning true all the time. What am I doing wrong?





Creating class instances stored in a list

So first I make an ArrayList. (? means that I don't know what should be there, keep reading)

ArrayList<?> arrayList = new ArrayList<?>();

So this will store class name of abstract class Class, so for example it might stores ExtendedClass1 or ClassExtended2.

Later I iterate through that ArrayList and create new objects with the name stored in arraylist

for (int i = 0; i < arrayList.size(); i++) {
    new arrayList.get(i); // Takes the class name and makes new object out of it
}

How can I actually do it?





How to inove methods with annotation parameter prioritet

How to inove methods with annotation parameter prioritet?

Got testmethods, which i should invoke with java reflection:

public class Testmethods {

//There are eight method, should be invocen with value prioritet.
//First method(1), last method(8)

//first method
@Test(8)
public void method1(){
    System.out.println("test");
}
.
.
.
.
//last method
@Test(1)
public void method8(){
    System.out.println("test7");
}

Annottation class with int parametr prioritet:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
    int value();
}

Try to invoce it with loop:

   private static void start(Class c) throws Exception {
        c = Testmethods.class;
        Method[] methods = c.getDeclaredMethods();

        int before = 0;
        int after = 0;
        int annoValue = 0;

        for (Method m : methods) {
            if (m.isAnnotationPresent(BeforeSuite.class)) {
                before++;
            }
            if (m.isAnnotationPresent(AfterSuite.class)) {
                after++;
            }

            if (m.isAnnotationPresent(BeforeSuite.class) && before > COUNT || m.isAnnotationPresent(AfterSuite.class) && after > COUNT) {
                throw new RuntimeException("more then one");
            }

            if (m.isAnnotationPresent(BeforeSuite.class) && m.getAnnotation(BeforeSuite.class).value() == 10) {
                m.invoke(c.newInstance());
            }
         }


//loop to invoce.  
//Loop invoce it in random order.       
            for (int i = 1; i < 9; i++) {
            if (methods[i].isAnnotationPresent(Test.class) && (methods[i].getAnnotation(Test.class).value() < i)) {
                methods[i].invoke(c.newInstance());
            }
        }
    }

But it's not work propertly.

How to inove methods with annotation parameter prioritet?





golang dynamicly create struct of some type and unmarshal json into that instance

I try to create an struct instance at run time. The instance has been created successfully, but I can't unmarshal json into it.

type Test struct {
    Name string `json:"name,omitempty"`
}

func create(a interface{}) {
    aType := reflect.TypeOf(a).Elem()
    elType := aType.Elem()

    f := reflect.Indirect(reflect.New(elType))

    b := []byte(`{"name": "go"}`)

    err := json.Unmarshal(b, &f)
    fmt.Println(err, f)
}

func main() {
    l := []Test{}
    create(&l)
}





dimanche 17 juin 2018

How to give input for scanner class in reflection method for dynamic code execution

I was doing a project which is a web compiler and I am using reflection method for code execution. but I am not able to pass any value for scanner class in order to read from the java program. how can I pass a value for scanner class using method of reflection api

  String paramsObj[] = {"hellooo"};
  File f = new File("/location/to/class");
  URL[] cp = {f.toURI().toURL()};
  URLClassLoader urlcl = new URLClassLoader(cp);
  Class clazz = urlcl.loadClass(filename.trim());
  Object iClass = clazz.newInstance();
  Class[] argTypes = new Class[] { String[].class };
  String[] mainArgs ={"Abcd","defg"};
  Method thisMethod = clazz.getMethod("main",argTypes);
  thisMethod.invoke(null,(Object)mainArgs);

this is how i am calling main method , can anyone please help me to solve this ...?





samedi 16 juin 2018

Access private members of the generic instance within a generic class via reflection

I have looked at potentially duplicate questions, and this problem is not answered in any of them including Accessing Properties Through Generic Type Parameters

TLDR; typeof(T).GetProperty(propertyName) does not work within a generic class when propertyName of T is not declared public. Is there a workaround for this?

I have implemented an extension method that produces an IOrderedQueryable from a supplied string that contains the desired columns for sorting in an Entity Framework environment. The goal was to allow Order By clauses to be written in string form such as "+Age,+State,-Name" and produce the necessary expression to sort Entity Framework results by Age, State, and Name (descending), instead of having to write:

.OrderBy(m=>m.Age).ThenBy(m=>m.State).ThenByDescending(m=>m.Name).

The problem comes in when I try to access a class property that is marked internal. I cannot seem to find any way to force reflection to find that internal property.

In this particular case I have a datetime field in the database which is stored UTC but I want the end user to work with it in local time, so the value startTime, an internally scoped property is bound to the database and StartTime serves as a public accessor and provides access to the startTime value performing the necessary mapping to local time. I have a class defined as follows:

public class TimeInterval { 
   //other properties...
   internal startTime { get; set; } // bound to database, stores time in UTC
   public StartTime { 
      get { /*convert startTime to local time*/; } 
      set { /*convert value back to UTC and store in startTime*/;  }
   }
}

With EF I can write .OrderBy( m=>m.startTime ) and it works as expected; of course I cannot use .OrderBy( m=>m.StartTime ) because it is derived.

Within my extension function whose signature is

static public IOrderedQueryable<T> ParseOrderBy<T>( 
   this IQueryable<T> query, 
   string orderBy 
   )

which I would call using :

var query = query.ParseOrderBy<TimeInterval>( "startTime" );

my call to obtain the property reference to build a lamba expression returns null.

var property = typeof( T ).GetProperty( "startTime" );

property comes back null for anything that is not explicitly public.

The extension method is in the same namespace and assembly as the classes I expect it to operate.





Do we have a reflective tower in Julia?

Julia borrows quite heavily from Lisp. I was wondering if Julia's reflection has the reflective tower ability.

3-Lisp is implemented as an infinite stack of meta-circular interpreters, each one executing the one under itself and the bottom one (level 1) executing the end-user program (level 0). The only way to get back to the original interpreter is when the continuation is called inside the reflective lambda's body. If the continuation is not called then the program just stays in the upper interpreter.

This is referred to as “being stuck" at a meta level. Is this implemented in Julia? If it is, how does Julia avoid getting stuck at the meta level?





vendredi 15 juin 2018

How do I get the typeparam names from a generic type definition?

Suppose I have a generic type definition as such:

var type = typeof(IReadOnlyDictionary<,>)

How would I get the typeparam name of the generic arguments? In the example above, I'm looking for "TKey" and "TValue"

for typeof(IList<>) I am expecting "T"

Is there any way, using reflection, to get these strings?





EntityFrameworkCore is there a way to create EnumToStringConverter without passing the enum type as generic?

I am trying to use EntityFrameworkCore ORM to interact with my databases. By default, EntityFrameworkCore seems to store enum as int instead of string.

However, I would like to store the value in the database as a string. I can see that EntityFrameworkCore ships with a converter called EnumToStringConverter.

I am trying to use reflection to setup the model builder so I don't have to manually build each model.

The issue that I am running into is that EnumToStringConverter accepts a generic type which must be an enum. But since I am trying to use reflection here I am unable to pass the enum type when creating the converter

Here is what my code look like so far

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // Get all DbSet<> properties that are defined in the DbContext
    var modelTypes = typeof(DataContext).GetProperties()
                                        .Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
                                        .Select(x => x.PropertyType.GetGenericArguments().First())
                                        .ToList();

    foreach (Type modelType in modelTypes)
    {
        var properties = modelType.GetProperties();

        foreach (var property in properties)
        {
            if (IsPrimaryKey(property))
            {
                // At this point we know that the property is a primary key
                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .UseSqlServerIdentityColumn()
                            .Metadata.BeforeSaveBehavior = PropertySaveBehavior.Ignore;

                continue;
            }

            if (property.PropertyType.IsEnum)
            {
                // At this point we know that the property is an enum.
                // Add the EnumToStringConverter converter to the property so that
                // the value is stored in the database as a string instead of number 
                var converter = new EnumToStringConverter(); // if somehow I can change this code to something like var `new EnumToStringConverter(property.PropertyType);` the code would work

                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .HasConversion(converter);

                continue;
            }

        }
    }
}

The only issue with the above code is how EnumToStringConverter is constructed. If somehow I can provide a Type to the constructor of the EnumToStringConverter instead of passing it as a generic argument that would solve the problem.





Capture caller source line with template parameters deduction

I need to capture the caller source line for a templated addition operator. The code below works fine without templates but complains about dependent type when templates are used.

I'm looking for any workaround or hack that can enable me to execute the simple add operation below and report the caller source line in C++.

#include <iostream>

template <unsigned N>
class widget {
  int data_;
public:
  class proxy {
  public:
    proxy(widget &a, int l = __builtin_LINE()) : a(a), l(l) {}
    widget &a;
    int l;
  };
  widget(int data) : data_(data << N) {}
  template <unsigned M>
  widget operator+(const typename widget<M>::proxy &other) {
    std::cout << "operator+ called at line " << other.l << std::endl;
    return widget((data_ >> N) + (other.a.data_ >> M));
  }
};

int main() {
  widget<2> x(5);
  widget<3> y(6);
  auto z = x + y;
  return 0;
}

compiler error: "template argument deduction/substitution failed"





Change import static statement object instance via reflection

There is a Basic interface Basic.java as:

public interface Basic {
    public void doWork();
}

Another interface extends Basic interface as, where Factory.getMessageInstance() return an instance of type interface A.

public interface A extends Basic {
    A InstanceA = Factory.getMessageInstance();
}

In my Foo.java method bar()

import static org.company.InstanceA;

public void bar(){
    InstanceA.doWork();
}

Is that possible to override InstanceA or its doWork() implementation via Java reflection?





Java/scala Reflections getting all methods within a specific class which are annotated

I am writing an event message handler. To handle the reflection, I am using Reflections API (https://github.com/ronmamo/reflections).

Each event listener is a method annotated by

public @interface ListenTo {}

and a listener would follow a theme such as:

class Example {
  EventHandler.get.registerListener(this)

  @ListenTo
  def onEvent(e: SomeEvent): Unit 
}

and the code to register the listeners is as follows:

private var listeners: mutable.ListBuffer[(Any, List[Method])] = ListBuffer()

def registerListener(obj: Any): Unit = {
  listeners += Tuple2(obj, getAllMethods(obj.getClass, withAnnotation(classOf[ListenTo])).asScala.toList)
}

However, on registering a listener, the object is saved within the tuple, but no methods with it, does anybody know why?





Can I apply BABYLON textures and materials to vertices of a ground?

I'm new in babylon.js and trying to create a dynamic water surface.

I succeeded in creating waves on a flat surface (using a ground and updateVerticesData).

What i need know is doing reflections (thought about reflection textures) and refractions (tought about mirrors). Both are done by babylon by using planes but my surface is not flat but dynamic.

Can I apply the correct reflections and refractions to the vertices or to the triangles componing my ground ?

Is it ok to do that in a realtime rendering ?

Thanks for any suggestions !





jeudi 14 juin 2018

Cannot find classes in a package using Class.forName()

Using Java I am implementing a Page Factory object for selenium testing that takes the name of a page object and instantiates it through reflection for use by Cucumber step definitions. The problem I am having is that the code below cannot find the declared class. Both the object PageFactory which contains this code and the page object LoginPage reside in a package called pages.

 /**
 * This method take a string containing a Page Object class name (case-sensitive) and returns an instance of the Page Object.
 * This allows us to operate on pages without knowing they exist when we write step definitions.
 * @param choice String
 * @return Page Object cast as a Page
 */
public static Page getPage(String choice) {
    Page entity = null;

    try {
        entity = (Page) Page.forName(choice).newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return entity;
}

I receive a stack trace with java.lang.ClassNotFoundException: LoginPage as the beginning of the error. If I change the entity creation to the following code, then it works.

        private static String packageName = "pages";
        entity = (Page) Page.forName(packageName + "." + choice).newInstance();

The problem is that I want to organize my pages. When I create pages.mywebsite and place LoginPage within that, PageFactory won't know where to find the file.

Leaving aside the problem that I could have two namespaces pages.mywebsite and pages.myotherwebsite that both have a LoginPage object, how can I find the files I want without declaring the exact package, and just say "Look in this package and the ones below for the class"?





Getting Scalatest method info via reflection

I'd like to get some information about the tests in the classpath. I'd like it to look something like:

class-name:method-name:test-string

For example:

MyTestClass:{some anonymous class/method}:A Stack should pop values in last-in-first-out order

I can interrogate the FlatSpec easily enough to get the names and descriptions, but not the methods themselves. If I use reflection, I can find the methods, but I don't know what they do because of the anonymous names.

Does anyone know how this might be done?





Accessing a class in other namespace but same solution [duplicate]

This question already has an answer here:

Despite the many examples I still do not get it.

I got 1 visualstudio solution with multiple projects inside

1 of those projects is a console application

namespace Test

--> assembly name is Test

1 of those projects is a class library

namespace Mayhem

--> assembly name is Mayhem

The class library has multiple classes

namespace Mayhem
{
    public class Step1
    {
       public int Id { get; set; }
       public string Title { get; set; }
    }
}

I can access the class library from the console application. But I would like to access the class library through Reflection. Based on some other solutions I came up with something like this, but it still gives me a TypeLoadException

namespace Test
{
    class Program
    {
        private static void Main(string[] args)
        {
            string[] ClassArray = new string[] { "Mayhem.Step1", "Mayhem.Step2" };

        foreach (var item in ClassArray)
        {
            Type type = Type.GetType(item, true);

            object instance = Activator.CreateInstance(type);

            PropertyInfo prop = type.GetProperty("Title");

            prop.SetValue(instance, item, null);

            Console.WriteLine(SetSegment.ToMessageSegment(instance));
        }

        }
    }
}

Question: what am I doing wrong?





Running an ASP.NET using dynamically loaded assemblies

How could I run an IIS express website using purely dynamically generated assemblies and webconfigs.

For example, I could dynamically run a Console Application by doing:

Assembly pAssembly = Assembly.LoadFrom([[ApplicationPath]]).

MethodInfo pMainMethod = pAssembly.GetType("Program").GetMethod("Main);

pMainMethod.Invoke(null, new Object[1] { new String[0]; });

I can even dynamically load the app config using something like in this question: Change default app.config at runtime

How could I do something similar for dynamically running an IIS express website using dynamically generated assemblies (these assemblies might not necessarily be on the file system, since they may have been fetched remotely).





Reflection in php5 or php7

How to do reflection in php5 and get more infos about variables types ?

$reflector = new ReflectionMethod(new MyClass(),'methodName');
$params = $reflector->getParameters();

foreach( $params as $key=>$value):
  //-want to get something like $value->type
  echo $value->name;
endforeach;





java reflections to get all user created class variables only

I am trying to use reflections to create a function that checks all custom made class variables to see if they have valid values based on pattern "[0-9a-zA-Z_]+"

I found some code templates and adapted to my code and looks like this

UserClass uc = new UserClass();
Class clazz = uc.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String name = field.getName();
                Object value;
                try {
                    value = field.get( uc );
                     System.out.printf("Field name: %s, Field value: %s%n", name, value);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

My UserClass looks like

@Entity
public class UserClass implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    private String descr;

    private String name;

    @OneToMany(mappedBy="userClassId",fetch=FetchType.LAZY)
    private List<packages> packagesList;

I get the UserClass variable names and values normally but the problem is that it also takes some other variables which i dont care about like pcInheritedFieldCount,pcFieldNames and others

My solution is to check if the variable name starts if pc to ignore it but i wanted to know if there is a right/the best way to get only these variables i declared in my class definition.





Libgdx ClassReflection.newInstance don't work with hmtl version

I'm working on an application that must work on desktop, android and web browser.

On Desktop and Android I have no problem, everything work fine. But on the HTML version, the newinstance of a class won't work. I don't understand why.

Here is my code:

public static Node newInstanceGdx(Class<? extends Node> nodeModel) throws ReflectionException {
    if (nodeModel != null)
        try {
            return ClassReflection.newInstance(nodeModel);
        } catch (Exception e) {
            e.printStackTrace();
            Gdx.app.setLogLevel(Application.LOG_DEBUG);

            Gdx.app.log("Reflection", "Can't initialize Node class :  " + (Node.class).getName());
        }
    return null
}

And here is myGame.gwt.xml code :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module>
    <source path="fr/EU/Game" />
    <extend-configuration-property name="gdx.reflect.include" value="com.me.reflected.ReflectedClass" />
    <extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.reflect.ClassReflection"/>
    <extend-configuration-property name="gdx.reflect.include" value="com.badlogic.gdx.utils.reflect.ReflectionException"/>

</module>

It always return "null" for the html version, but on the other version, everything work.

Thanks in advance for your help.





java : Invoke method with an user defined class array parameter using reflection

I am attempting to write a method the executes a method by passing an array of user defined class as arguments to the method using reflection.

Class[] argTypesList = new Class[] {String[].class, String[].class, MyClass[].class};       
Method methodToExecute = classToCall.getDeclaredMethod(“Method1”, argTypesList);

Method1 is : 
Method1(String[] a, String[] b, MyClass[] myclass)

Here third param is of user defined class array.

Class myClass= Class.forName("somepackage.MyClass");

argTypesList = new Class[] {String[].class, String[].class, myClass[]};

gave below error

error: '.class' expected


with myClass[].class gives cannot find symbol for myClass





mercredi 13 juin 2018

Expression as function parameter for property and object type

I require a function which takes as parameter the following things:

  • The type of the object
  • Name of a specific property of the object

Currently I do it in a rather inconvenient and long way:

public static void Add<TEntity, TProperty>(TEntity e, Expression<Func<TProperty>> expression)
{
     var type = typeof(TEntity);
     var propertyName = ((MemberExpression) expression.Body).Member.Name;
}

Which results in a function call like this: Add(Foo, () => Foo.Bar);

However with that solution I have a couple problems:

  • It gets really long when I have a object like this: Add(Foo.Bar.Element.Type, () => Foo.Bar.Element.Type.Name) and looks quite ugly.
  • It isn't ensured that propertyName is a property of the object's type.
    • I actually don't do anything really with e so it's not used.

Is there a better solution to this?





Create BiConsumer as Field setter without reflection

I try to get the maximum performance in one of my scripts, without doing a major refactor.

I spotted method that creates a BiConsumer from a Field using reflection.

return (c, v) -> {
    try {
        field.set(c, v);
    } catch (final Throwable e) {
        throw new RuntimeException("Could not set field: " + field, e);
    }
};

Reflection has the reputation of being slow. So I though I could use the method handles.

Lookup lookup = MethodHandles.lookup();
MethodHandle mh = lookup.unreflectSetter(field);
return (c, v) -> {
    try {
        mh.invoke(c, v);
    } catch (final Throwable e) {
        throw new RuntimeException("Could not set field: " + field, e);
    }
};

Which is already a tiny bit faster. However BiConsumer is a FunctionalInterface which could just be generated somehow.

public static <C, V> BiConsumer<C, V> createSetter(final MethodHandles.Lookup lookup,
        final Field field) throws Exception {
    final MethodHandle setter = lookup.unreflectSetter(field);
    final CallSite site = LambdaMetafactory.metafactory(lookup,
            "accept",
            MethodType.methodType(BiConsumer.class),
            MethodType.methodType(void.class, Object.class, Object.class), // signature of method BiConsumer.accept after type erasure
            setter,
            setter.type()); // actual signature of setter
    return (BiConsumer<C, V>) site.getTarget().invokeExact();
}

However then I get an Exception which I don't really understand

Exception in thread "main" java.lang.invoke.LambdaConversionException: Unsupported MethodHandle kind: putField org.sample.dto.TestDTO.name:(String)void
    at java.lang.invoke.AbstractValidatingLambdaMetafactory.validateMetafactoryArgs(AbstractValidatingLambdaMetafactory.java:182)
    at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:303)
    at org.sample.bench.MyBenchmark.createSetter(MyBenchmark.java:120)
    at org.sample.bench.MyBenchmark.main(MyBenchmark.java:114)

In which way do I have to generate that setter correctly to increase the performance. (without actually adding a setter method)





How can I call golang struct field's function?

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) Foo() {
    fmt.Println("foo")
}

type A struct {
    Ts T
}

func main() {
    var t T
    var a A = A{Ts: t}
    val := reflect.ValueOf(&a).Elem()
    for i := 0; i < val.NumField(); i++ {
        vf := val.Field(i).Addr()
        fmt.Println(vf.Type())
        fmt.Println(vf.Kind())
        reflect.ValueOf(vf).MethodByName("Foo").Call([]reflect.Value{})
    }

}

$ go run reflect_call_1.go
*main.T ptr panic: reflect: call of reflect.Value.Call on zero Value

goroutine 1 [running]: reflect.flag.mustBe(0x0, 0x13)
/usr/local/go/src/reflect/value.go:201 +0xae reflect.Value.Call(0x0, 0x0, 0x0, 0xc420049f00, 0x0, 0x0, 0x0, 0x0, 0x40457c)
/usr/local/go/src/reflect/value.go:300 +0x38





Can I pass a class literal from a templated class as an argument for an annotation?

I have an annotation that takes a Class as value (the response field of @ApiResponse from springfox). The response I want mapped is a templated class (PageDTO<T>) but I can not get a class literal for my specific entity, e.g. PageDTO<BusinessClass>.class. The only option that works is defining another class: class Doc extends PageDTO<BusinessClass> and pass the value of Doc.class as parameter.

Is there a way of achieving the same result without defining a class for each annotated method?

I tried the double casting method, (Class<PageDto<BusinessClass>>)(Class<?>)PageDTO.class but it did not work.





mardi 12 juin 2018

Export libgdx project to HTML - did you forget to inherit a required module?

I try to export my libgdx game in HTML. I already export it on Android and desktop, and it works well. But when I execute ./gradlew html:dist, I have many errors like this one:

[ERROR] Line 75: No source code is available for type net.spookygames.gdx.gameservices.playtomic.PlaytomicServicesHandler; did you forget to inherit a required module?

net.spookygames.gdx.gameservices is a package which is next to my main package in core folder:enter image description here

I saw on documentation and on another question that I need use reflection by putting this line in my GdxDefinition.gwt.xml in html folder:

<extend-configuration-property name="gdx.reflect.include" value="net.spookygames.gdx.gameservices" />

But it didn't change anything.. Do I need to do something else? Thanks





How to get code execution graph and relevant time?

Let’s say I have a .NET exe application. Let’s say I have a complex calling structure E.g. method1 calls method2 etc and I want to inspect execution time.I want to plot the code execution graph into a text file. How can I do that? E.g.

Class1.Method1 (paramer1,parameter2)-> 5 took seconds to execute

Class2.Method2(parameter3)-> 2 took seconds to execute

I know there are tools like RedGate Ants memory profile. But can we do this without using a third-party tools or how can I create something like RedGate Ants memory profiler using .NET?





lundi 11 juin 2018

RetentionPolicy.RUNTIME doesn't exist?

Currently I'm working on a simple annotation, but for this I need to add the following annotation to the annotation to be able to use reflection on it:

@Retention(RetentionPolicy.RUNTIME)
public @interface Cmd {
    String permission() default "";
    String description() default "";
    String[] fireOn();
}

But for some reason this RetentionPolicy is not something that I can import and doesn't get recognized by the compiler at all.

On top of this, I got all information from official documents that also use the RetentionPolicy.RUNTIME enum.

Maybe this is a really stupid question, and I'm sorry for that. On the contrary I think more people run into this problem and can't find a clear solution.

So I'm looking forward to reactions to my issue that could clearify everything for me and other people.

-DutchJelly





Matlab get all Subclasses

is there a possibility in Matlab that I can get a List with all my Subclasses which derive/extend from a SuperClass? (in .NET I would do it with reflection)

Let's say I have the following SuperClass:

classdef UltraSuperClass < handle

and now I have the following SubClasses

classdef FirstSubClass < UltraSuperClass 
classdef SecondSubClass < UltraSuperClass 

Now it would be perfect if there exists something like

a = GetAllSubClassesFrom(UltraSuperClass)

and my result will be

a = [FirstSubClass , SecondSubClass]

anyone knows if this wonderful method exists?

Cheers





C# - Order By property by reflection [duplicate]

This question already has an answer here:

I have a database query providing me IQueryable object where T is anonymous data type like this:

var baseListQuery = (<...> select new {
    note = n, // class Note
    triggers = grp // class Trigger
})

Now I would like to sort this by different properties of Note (e.g. Note.Title) but my Note class can contain plenty of different properties. Property to be used as sorting element can be changed externaly and information about which one to use I will receive as a simple string. Currently I am using switch-case statement to evaluate received string and then select appropriate property to sort:

switch(SortBy) {
    ...
    case "Title": baseListQuery = baseListQuery.OrderBy(p => p.note.Title); break;
    ...
}

However, I am wondering if it is possible to to it in more general way, using reflection? I would like to check if Note contains property with the name of received string and if so, sort results appropriately. I have tried something like this:

var baseQueryType = baseListQuery.GetType();
var member = (baseQueryType.GetGenericArguments()[0]).GetProperty("note");
var member2 = member.PropertyType.GetProperty("Title"); // I would like to use GetProperty(SortBy);
baseListQuery = baseListQuery.OrderBy(p => member2);

Which will raise exception when calling for example baseListQuery.Count():

System.NotSupportedException: 'Unable to create a constant value of type 'System.Reflection.PropertyInfo'. Only primitive types or enumeration types are supported in this context.'

Is it possible to do this with reflection, and if so, can somebody explain me, what am I doing wrong?





Reflection is not giving count for Attribute wise properties

I am having class with list of properties with Column attribute and I am assigning value to other object as per below function. But it is coming 0 when I count with ColumnAttribute.

public static void PopulateModelWithNoNull(object sourceObj, object targetObj)
        {
            var sourceProperties = TypeDescriptor.GetProperties(sourceObj).Cast<PropertyDescriptor>()
                .Where(p => p.Attributes.OfType<ColumnAttribute>().Count() > 0);

            var targetProperties = TypeDescriptor.GetProperties(targetObj).Cast<PropertyDescriptor>()
                .Where(p => p.Attributes.OfType<ColumnAttribute>().Count() > 0);


            for (int i = 0; i < sourceProperties.Count(); i++)
            {
                if (sourceProperties.ElementAt(i).GetValue(sourceObj) != null)
                {
                    targetProperties.ElementAt(i).SetValue(targetObj,
                        sourceProperties.ElementAt(i).GetValue(sourceObj));
                }
            }
        }

If I count without ColumnAttribute, it is working fine and returns count. However, it is working fine in one another project solution. Any ideas?