mercredi 31 janvier 2018

How to know if object is a singleton in Kotlin?

I would like to define toString()in superclass so, that it detects that class instance is a singleton (an object) and print it's name.

Is it possible in Kotlin?





How to get class of Any? variable in Kotlin?

I want my equals to compare class too and I wrote

    override fun equals(other: Any?): Boolean {
        return this::class == other::class && ...

    }

unfortunately it swears

Expression in a class literal has a nullable type 'Any?', use !! to make the type non-nullable

But I want to compare with nulls too. What about glorious "null safety"? They forgot it for reflection? I didn't find ?:: operator or something.





Compare whether a class is a subclass of another class

Say I get a class instance with:

Class clazz = Class.forName("SomeClass");

And I have the following class structure:

interface SuperClass {}
class SomeClass implements SuperClass {}

How can I see whether my clazz object is a subclass of SuperClass.class?

Basically, here's what I want to achieve:

I have an interface of some type, and then various implementations of that interface. However, which implementation will be used for future processes in my application is a choice I'd like the user to make, so for now I have the very simplistic approach of forcing the user to type the implementation class name in a terminal. I then obviously need to check whether what he typed in actually is a class, and if it is, if it is an implementation of my interface. What do you think would be the best way to go about this?





Read properties of object at run time even when they are not initialized

I am interested in creating a class decorator in typescript that can hold the class members information at runtime, which is quite similar to reflection API in C# and Java. Consider following example

class Address {
   door: number;
}
class Order {
   id: number;
}
class Customer {
   id: number;
   name: string;
   present: Address;
   orders: Order[];
}

let x = new Customer();
console.log(x); // outputs an empty object and no properties are visible 
       // because properties are mapped to object only after initialization.

I would like to get property details of a class even when they are not initialized. is it possible using decorators? I am thinking to create Model decorator

@Model({
   id: Number.prototype,
   name: String.prototype,
   present: Address.prototype,
   orders: // challenge is How do I specify array of specific type? 
   // because arrays in javascript simply inherit from Array.prototype 
   // but it must be Array of Order.prototype
})
class Customer {
   id: number;
   name: string;
   present: Address;
   orders: Order[];
}

Is this a better approach? Are there any open libraries that solve this problem in typescript. Any help is greatly appreciated. What I would like to see the output is

class members {
    static show(o: any){
      // should loop through the properties of object even not initialized
    }
}

members.show(new Customer()); // should display all properties with default values; 
// null for reference types and values for value types





mardi 30 janvier 2018

How to get a parameter value passed as a reference with MethodInfo.Invoke when throws an exception in the invoked method

I would like to know what is the value of an out/ref parameter of a invoked method.

When the method is invoked without throws an exception, the value is received in the parameter, but I do not get the value when an exception throws in the invoked method. Invoking directly the method without Reflection, the value is received.

Am I doing something wrong or is this a .net limitation?

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        string[] arguments = new string[] { bool.FalseString, null }; 
        MethodInfo method = typeof(Program).GetMethod("SampleMethod");
        try
        {
            method.Invoke(null, arguments);
            Console.WriteLine(arguments[1]); // arguments[1] = "Hello", Prints Hello
            arguments = new string[] { bool.TrueString, null };
            method.Invoke(null, arguments);
        }
        catch (Exception)
        {
            Console.WriteLine(arguments[1]); // arguments[1] = null, Does not print
        }
        arguments[1] = null;
        try
        {
            SampleMethod(bool.TrueString, out arguments[1]);
        }
        catch (Exception)
        {
            Console.WriteLine(arguments[1]); // arguments[1] = "Hello"
        }
    }

    public static void SampleMethod(string throwsException, out string text)
    {
        text = "Hello";
        if (throwsException == bool.TrueString)
            throw new Exception("Test Exception");
    }
}





android.os.ServiceManager: ClassNotFoundException even with Java reflection

I have some sample code trying out Binder in Android here.

I know android.os.ServiceManager is hidden API. So I use reflection to access it. But even with reflection I have following exception:

java.lang.ClassNotFoundException: android.os.ServiceManager

So even with reflection I couldn't access android.os.ServiceManager. Or is there any configuration error in the Android.mk?

The code is adapted from here. Sorry the README.md is in Chinese. The repo is little bit old. So it's still using Android.mk, not gradle. Any advice?





Call Method Expression with Pointer to Struct as Receiver

There is func someFunc(v interface{}, fn interface{}) where v is a pointer to struct (say *A) and fn is a method expression (say (*A).method()). How to call fn with v as parameter (using reflect)?





How to make ktor-swagger work with generics?

I found this solution to generate swagger API docs from ktor routes: https://github.com/nielsfalk/ktor-swagger. However, it doesn't work if the response type contains generics. E.g.:

data class DataWrapper<T>(
    val data: T,
    val additionalInfo: Unit  // useless field, just for an example
)

data class Response(
    val users: DataWrapper<User>,
    val roles: DataWrapper<Role>
)

The only thing I managed to do is generate T as a placeholder for the generic type. Is there a way to patch ktor-swagger to make it "expand" generic types?





lundi 29 janvier 2018

Passing C# parameters which can "fit" an interface, but do not actually implement it

Note: I know this is an awful idea in practice; I'm just curious about what the CLR allow you to do, with the goal of creating some sort of 'modify a class after creating it' preprocessor.

Suppose I have the following class, which was defined in another assembly so I can't change it.

class Person {
    public string Greet() => "Hello!";
}

I now define an interface, and a method, like the following:

interface IGreetable {
    string Greet();
} 

// ...

void PrintGreeting(IGreetable g) => Console.WriteLine(g.Greet());

The class Person does not explicity implement IGreetable, but it could do without any modification to its methods.

With that, is there any way whatsoever, using Reflection, the DLR or anything else, in which an instance of Person could be passed successfully to PrintGreeting without modifying any of the code above?





Writing generic protobuf serializer in GoLang

I am trying to call the grpc method having arguments of context and custom struct. So, I am stuck how to unmarshal the byte[] into custom struct *DBLogging.Request using reflection given the function name and finally call the respective grpc method

Proto File :

    package DBLogging;

    service Logging {   
        rpc ReadLogs (Request)  returns  (Response)  {} 
    }

    message MetaData
    {  
       string Name  = 1;
       string Id    = 2;
    }

    message Request {
       MetaData LogValue  = 1;
    }

Code :

       type server struct{

        }

        func (s *server) ReadLogs(ctx context.Context, in *DBLogging.Request) (*DBLogging.Response, error) {

        }

        func GenericFoo(server interface {}, funcName string, ctx context.Context, args []byte) {

            method := reflect.ValueOf(server).MethodByName(funcName)

            // how to unmarshal the args in *DBLogging.Request using reflection

            // how to call the grpc function using about unmarshalled data and context

            response := method.Call(inputs, ctx) // how to call the grpc function here 
        }

        func main() {
                var objRequest = &DBLogging.Request{ LogValue : &DBLogging.MetaData {
                            Name         :  "Model",
                            Id :  "123|345",                
                        },          
                    }

                data, err := proto.Marshal(objReadRequest)
                GenericFoo(&server{}, "ReadLogs", context.TODO(), data) 
        }





Three.js howto realize a reflection effect

I'm trying to reproduce an effect like lolita.persona.co Someone know where i can find something similar/ready for three ?





dimanche 28 janvier 2018

How to Attach System.Console class to a running Process?

I'm trying to use external command line app in my application. Here is my code

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.UseShellExecute = false;
        startInfo.FileName = @"../../console.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;


        try
        {
            using (Process exeProcess = Process.Start(startInfo))
            {


                var title = Console.Title;
                exeProcess.WaitForExit();
            }
        }
        catch (Exception)
        {


        }

But the problem is after the process is started, I can't changing anything with System.Console class.

When I try to Debug on Console.Title line, Visual Studio telling me Console.Title is null.

I tried to "Attach to Process" in Debug Menu in Visual Studio and it worked but I just want to do it with code.

So how can I attach System.Console class to "exeProcess" ?

Edit: My running exe file's PID is 8086 and exeProcess's Id is 7248. Its loading external console app in my application but still have different PID's. How can i make them same PID?





Get a Swift class's property name as a String [duplicate]

This question already has an answer here:

How do I get the property name as a string?

class Person {
    var firstName: String
    var lastName: String
    var downloading: Bool

    func excludePropertiesFromCloud() -> [String] {
        return //here I want to return ["downloading"]
    }
}

I would like to avoid having to type return ["downloading"] to prevent errors if the name of the variable changes later on.

To get the class name you can use String(describing: Person.self), so I am looking at something similar for properties.





Java: Get the line of code defining an object

In a relatively complex project I have many runnables defined like

Runnable foo = () -> {
// bar
}

'foo' is passed through several objects and executed at some point. Now for debugging purposes, I'd like a smooth way of retrieving in what file and in what line the runnable has been initialized and that without adding any code into the runnable (like working with the stacktrace).

In other words, I need a function which tells where an object has been created. Is there any reflection method in Java for this purpose?

Huge thanks in advance!





Cast to a generic type

I have the following interfaces

public interface IMessageData {}

public interface IMessageSender<T> where T : class, IMessageData, new()
{
    Task<T> BuildType();
    Task SendMessage(T message);
}

and then a base implementation for the IMessageSender

public abstract class MessageSenderBase<T> : IMessageSender<T> where T : class, IMessageData, new()
{
    public MessageSenderBase() {
    }

    public abstract Task<T> BuildType();

    public async Task SendMessage(T message) {
        Console.WriteLine($"Sending {JsonConvert.SerializeObject(message)}");
        await Task.FromResult(0);
    }
}

To use these interfaces I usually create a new instance of a MessageData and create a specific implementation of MessageSenderBase like

public class MessageDataA : IMessageData {
    public MessageDataA() {
    }

    public string Description { get; set; }
}

and

public class ASender : MessageSenderBase<MessageDataA> {
    public override async Task<MessageDataA> BuildType() {
        MessageDataA result = new MessageDataA() { Description = "description" };
        return await Task.FromResult<MessageDataA>(result);
    }
}

At runtime I only have in configuration the names of the MessageSenderBase implementations and I need to create dynamically instances of these classes and invoke both methods. This is correctly achieved with this code:

var className = "ASender";
var buildMethodName = "BuildType";
var sendMethodName = "SendMessage";

Assembly assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetType(className);
var instance = Activator.CreateInstance(type);

//invoke build method
var buildMethodInfo = type.GetMethod(buildMethodName);
dynamic buildAwaitable = buildMethodInfo.Invoke(instance, null);
var returnedType = await buildAwaitable;

//invoke send method
var sendMethodInfo = type.GetMethod(sendMethodName);
dynamic sendAwaitable = sendMethodInfo.Invoke(instance, new[] { returnedType });
await sendAwaitable;

My questions:

  1. can I cast the var instance = Activator.CreateInstance(type); to a stronger type instead of leaving it as var? This would avoid me to call methods by using MethodInfo and Invoke.
  2. As a further suggestion is there any way to make this design more strong typed?




samedi 27 janvier 2018

Can you instantialise a `Data` class's data inside Ruby?

An application I use at work has an embedded Ruby engine. The company have also embedded several Ruby C add-ons into the engine. The application has made several methods available in the UI mode, however not all of them. The methods are still there in the UI, however when calling them they raise an error:

Error: This method cannot be used within the User Interface

I would like to document which of these is usable within the User Interface and which are not. So I made this function:

def try(object,method,args)
    begin
        object.method(method).call(*args)
    rescue Exception => e
        message = e.to_s
        if(message == "Error: This method cannot be used within the User Interface"
            puts "#{object.to_s}::#{method.to_s} is not runnable in the UI"
        else
            puts "#{object.to_s}::#{method.to_s} is runnable in the UI"
        end
    end
end

This works great for static methods of classes! For instance, a class such as:

class A
    def A.greatMethod(a,b)
        puts "hello #{a} and #{b}"
    end
end

Could be tested like:

try(A,:greatMethod,[1,2]) #=> A::greatMethod is runnable in the UI

However, this doesn't work for instance methods of C-addons! For example:

try(MSCollection.new,:each,[1])

returns:

Error: wrong argument type MSCollection (expected Data)

Currently the only work around I have is to get a MSCollection object legitimately. For example:

col = Application.getWindows() #=> Returns collection of window objects
try(col,:each,[1]) #try method

Ideally I would be able to do something along the lines of:

try(constructIntoData(MSCollection),:each,[1])

as there are many objects to test. In the end, ideally I'd be able to do something like this:

Module.constants.each do |const|
    if const.to_s[/MS.+/]
        cls = Module.const_get(const) #class
        methods = cls.singleton_methods - Object.methods
        instance_methods = cls.instance_methods - Object.methods
        methods.each do |method|
            args = getTestArgs(cls,method)
            try(cls,method,args)
        end
        icls = constructIntoData(cls)
        instance_methods.each do |method|
            args = getTestArgs(cls,method)
            try(icls,method,args)
        end
    end
end

Any ideas?





vendredi 26 janvier 2018

Java Reflection with Lists

I have an object which is basically collection and I want to create new instance of that collection and add elements to it. The thing is, I don't know how to create an instance of that collection or if it is even possible. I managed to find out the canonical name for that collection class by calling object.getClass().getCanonicalName();





Operation on "Assembly" is very slow when another application already use them

I've some operation that I'm doing with reflection(this will be changed end of year, but in between I've to find a solution), so we load the DLL of one directory( with AppDomain.CurrentDomain.GetAssemblies()), then we filter it to check it contains some DLL.

The filter is based on some specific attribute present in the AssemblyInfo, then we check each type of the assembly(assembly.GetTypes()) and check it implements a specific interface.

If it does we instantiate the object and execute a method on it:

if (type.GetInterface(typeof(IAssemblyInitializer).FullName) == null)
{
    return ;
}
bool isCompatible = !type.IsAbstract;
if (!type.IsClass)
{
    return
}
if (type.GetConstructor(new Type[0]) == null)
{
    return
}

IAssemblyInitializer initializer = Activator.CreateInstance(type, new object[0]) as IAssemblyInitializer;
if (initializer != null)
{
    initializer.InitializeAssembly();
}

Everything seems to work, but when we have another application already started(and having done this exact same procedure), the execution of this takes a lot longer(like 2 minutes instead of 20 seconds).

So my question: Why does it seems we are influenced on the fact that another application has already loaded thoses assemblies, and what can we do against ?

Thanks!





jeudi 25 janvier 2018

Using reflection on generics recursively

I have the following classes:

public class BaseDataEntity
{
    private List<string> _Changes = new List<string>();

    public IEnumerable<string> GetChanges()
    {
        return _Changes;
    }

    public bool HasDataChanged
    {
        get { return (GetChanges().Count() > 0); }
    }

    public bool HasChildRecords
    {
        get { return (GetType().GetChildRecords().Count() > 0); }
    }
}

public class ChildRecords : IList<T> where T : BaseDataEntity
{

}

And a few helper methods:

public static PropertyInfo[] GetChildRecords(this Type aType)
{
    return aType.GetProperties().Where(pi => pi.IsChildRecords()).ToArray();
}

public static bool IsChildRecords(this PropertyInfo info)
{
    return (info.GetCustomAttributes(typeof(ChildRecordsAttribute), false).Length > 0);
}

What I'm trying to do is implement a property called HaveChildRecordsChanged using reflection. My question is how would I go about using reflection to check the HasDataChanged property of all ChildRecords of arbitrary depth?

I tried something like:

var isChanged = false;

foreach (var info in GetType().GetChildRecords())
{
    var childRecordObject = info.GetValue(this, null);
    var childRecords = childRecordObject as ChildRecords<BaseDataEntity>;   //cannot unbox this, it evaluates as null
    if (null != childRecords && childRecords.Any(x => x.HasDataChanged))
    {
        isChanged = true;   //never hit
    }
}

return isChanged;   





Linq dynamic expression for filtering navigation properties and collections

I'm trying to add filtering functionality to my web api. I have two classes as base class

Global one is:

public abstract class GlobalDto<TKey, TCultureDtoKey, TCultureDto> :
    Dto<TKey>,
    IGlobalDto<TKey, TCultureDtoKey, TCultureDto>
    where TCultureDto : ICultureDto<TCultureDtoKey, TKey>, new()
{
    public virtual IList<TCultureDto> Globals { get; set; }        
}

and the cultured one is:

public abstract class CultureDto<TKey, TMasterDtoKey> :
    SubDto<TKey, TMasterDtoKey>,
    ICultureDto<TKey, TMasterDtoKey>
{
    public int CultureId { get; set; }
}

also SubDto class is:

public abstract class SubDto<TKey, TMasterDtoKey> : Dto<TKey>, ISubDto<TKey, TMasterDtoKey>
{
    public TMasterDtoKey MasterId { get; set; }
}

the scenario I'm trying is filtering the IQueryable GlobalDto dynamically and also filter by its

 IList<TCultureDto> Globals { get; set; }

eg:

public class CategoryDto : GlobalDto<int, int, CategoryCultureDto>, IDtoWithSelfReference<int>        
{
    public int? TopId { get; set; }

    [StringLength(20)]
    public string Code { get; set; }

    public IList<CategoryCoverDto> Covers { get; set; }

}

public class CategoryCultureDto : CultureDto<int, int>
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }        
}

I have tried this answer here and also lot of things but I couldn't make it.

I have property name, operation type (eg: contains, startswith) and comparing value from querystring so it has to be dynamic for various propertynames and various operation types like co(contains) and infinite values like foo.

http://localhost:5000/categories?search=name co foo

after this request

IQueryable<CategoryDto> q;//query
/* Expression building process equals to q.Where(p=>p.Globals.Any(c=>c.Name.Contains("foo")))*/
return q.Where(predicate);//filtered query

But I couldnt make it for globals

Edit: Code I used for doing this.

[HttpGet("/[controller]/Test")]
    public IActionResult Test()
    {
        var propName = "Name";
        var expressionProvider = new GlobalStringSearchExpressionProvider();
        var value = "foo";
        var op = "co";

        var propertyInfo = ExpressionHelper
            .GetPropertyInfo<CategoryCultureDto>(propName);
        var obj = ExpressionHelper.Parameter<CategoryCultureDto>();

        // Build up the LINQ expression backwards:
        // query = query.Where(x => x.Property == "Value");

        // x.Property
        var left = ExpressionHelper.GetPropertyExpression(obj, propertyInfo);
        // "Value"
        var right = expressionProvider.GetValue(value);

        // x.Property == "Value"
        var comparisonExpression = expressionProvider
            .GetComparison(left, op, right);

        // x => x.Property == "Value"
        var lambdaExpression = ExpressionHelper
            .GetLambda<CategoryCultureDto, bool>(obj, comparisonExpression);
        var q = _service.GetAll(); //this returns IQueryable<CategoryDto>

        var query = q.Where(p => p.Globals.CallWhere(lambdaExpression).Any());

        var list = query.ToList();

        return Ok(list);
    }


public class GlobalStringSearchExpressionProvider : DefaultSearchExpressionProvider
{
    private const string StartsWithOperator = "sw";
    private const string EndsWithOperator = "ew";
    private const string ContainsOperator = "co";

    private static readonly MethodInfo StartsWithMethod = typeof(string)
        .GetMethods()
        .First(m => m.Name == "StartsWith" && m.GetParameters().Length == 2);

    private static readonly MethodInfo EndsWithMethod = typeof(string)
        .GetMethods()
        .First(m => m.Name == "EndsWith" && m.GetParameters().Length == 2);

    private static readonly MethodInfo StringEqualsMethod = typeof(string)
        .GetMethods()
        .First(m => m.Name == "Equals" && m.GetParameters().Length == 2);

    private static readonly MethodInfo ContainsMethod = typeof(string)
        .GetMethods()
        .First(m => m.Name == "Contains" && m.GetParameters().Length == 1);

    private static readonly ConstantExpression IgnoreCase
        = Expression.Constant(StringComparison.OrdinalIgnoreCase);

    public override IEnumerable<string> GetOperators()
        => base.GetOperators()
            .Concat(new[]
            {
                StartsWithOperator,
                ContainsOperator,
                EndsWithOperator
            });

    public override Expression GetComparison(MemberExpression left, string op, ConstantExpression right)
    {
        switch (op.ToLower())
        {
            case StartsWithOperator:
                return Expression.Call(left, StartsWithMethod, right, IgnoreCase);

            // TODO: This may or may not be case-insensitive, depending
            // on how your database translates Contains()
            case ContainsOperator:
                return Expression.Call(left, ContainsMethod, right);

            // Handle the "eq" operator ourselves (with a case-insensitive compare)
            case EqualsOperator:
                return Expression.Call(left, StringEqualsMethod, right, IgnoreCase);

            case EndsWithOperator:
                return Expression.Call(left, EndsWithMethod, right);

            default: return base.GetComparison(left, op, right);
        }
    }
}


public static class ExpressionHelper
{
    private static readonly MethodInfo LambdaMethod = typeof(Expression)
        .GetMethods()
        .First(x => x.Name == "Lambda" && x.ContainsGenericParameters && x.GetParameters().Length == 2);

    private static readonly MethodInfo[] QueryableMethods = typeof(Queryable)
        .GetMethods()
        .ToArray();

    private static MethodInfo GetLambdaFuncBuilder(Type source, Type dest)
    {
        var predicateType = typeof(Func<,>).MakeGenericType(source, dest);
        return LambdaMethod.MakeGenericMethod(predicateType);
    }

    public static PropertyInfo GetPropertyInfo<T>(string name)
        => typeof(T).GetProperties()
        .Single(p => p.Name == name);

    public static ParameterExpression Parameter<T>()
        => Expression.Parameter(typeof(T));

    public static ParameterExpression ParameterGlobal(Type type)
        => Expression.Parameter(type);

    public static MemberExpression GetPropertyExpression(ParameterExpression obj, PropertyInfo property)
        => Expression.Property(obj, property);

    public static LambdaExpression GetLambda<TSource, TDest>(ParameterExpression obj, Expression arg)
        => GetLambda(typeof(TSource), typeof(TDest), obj, arg);

    public static LambdaExpression GetLambda(Type source, Type dest, ParameterExpression obj, Expression arg)
    {
        var lambdaBuilder = GetLambdaFuncBuilder(source, dest);
        return (LambdaExpression)lambdaBuilder.Invoke(null, new object[] { arg, new[] { obj } });
    }

    public static IQueryable<T> CallWhere<T>(this IEnumerable<T> query, LambdaExpression predicate)
    {
        var whereMethodBuilder = QueryableMethods
            .First(x => x.Name == "Where" && x.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T));

        return (IQueryable<T>)whereMethodBuilder
            .Invoke(null, new object[] { query, predicate });
    }

    public static IQueryable<T> CallAny<T>(this IEnumerable<T> query, LambdaExpression predicate)
    {
        var anyMethodBuilder = QueryableMethods
            .First(x => x.Name == "Any" && x.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T));
        return (IQueryable<T>) anyMethodBuilder
            .Invoke(null, new object[] {query, predicate});
    }


}

Exception is:

{
"message": "Could not parse expression 'p.Globals.CallWhere(Param_0 => Param_0.Name.Contains(\"stil\"))': This overload of the method 'ImjustCore.CrossCutting.Extensions.Expressions.ExpressionHelper.CallWhere' is currently not supported.",
"detail": "   at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.GetNodeType(MethodCallExpression expressionToParse)\n   at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(String associatedIdentifier, IExpressionNode source, IEnumerable`1 arguments, MethodCallExpression expressionToParse)\n   at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier)\n   at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNode(Expression expression, String associatedIdentifier)\n   at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier)\n   at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree)\n   at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)\n   at Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit(Expression expression)\n   at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression`1 node)\n   at System.Linq.Expressions.Expression`1.Accept(ExpressionVisitor visitor)\n   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)\n   at Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit(Expression expression)\n   at Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Process(Expression expressionTree, INodeTypeProvider nodeTypeProvider)\n   at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.ProcessArgumentExpression(Expression argumentExpression)\n   at System.Linq.Enumerable.SelectListPartitionIterator`2.ToArray()\n   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\n   at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(String associatedIdentifier, IExpressionNode source, IEnumerable`1 arguments, MethodCallExpression expressionToParse)\n   at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier)\n   at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree)\n   at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, INodeTypeProvider nodeTypeProvider, IDatabase database, IDiagnosticsLogger`1 logger, Type contextType)\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_0`1.<Execute>b__0()\n   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)\n   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)\n   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)\n   at Remotion.Linq.QueryableBase`1.GetEnumerator()\n   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)\n   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\n   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\n   at ImjustCore.Presentation.Api.Controllers.CategoriesController.Test() in /Users/apple/Desktop/Development/Core/ImjustCore/ImjustCore/ImjustCore.Presentation.Api/Controllers/CategoriesController.cs:line 87\n   at lambda_method(Closure , Object , Object[] )\n   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)\n   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()\n--- End of stack trace from previous location where exception was thrown ---\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\n   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()\n--- End of stack trace from previous location where exception was thrown ---\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)\n   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()\n--- End of stack trace from previous location where exception was thrown ---\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\n   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextExceptionFilterAsync>d__23.MoveNext()"
}

When I apply the lambda expression directly to IQueryable of CategoryDto with same extension classes above

with:

[HttpGet("/[controller]/Test")]
    public IActionResult Test()
    {
        var propName = "Code";
        var expressionProvider = new StringSearchExpressionProvider();
        var value = "foo";
        var op = "co";

        var propertyInfo = ExpressionHelper
            .GetPropertyInfo<CategoryDto>(propName);
        var obj = ExpressionHelper.Parameter<CategoryCultureDto>();

        // Build up the LINQ expression backwards:
        // query = query.Where(x => x.Property == "Value");

        // x.Property
        var left = ExpressionHelper.GetPropertyExpression(obj, propertyInfo);
        // "Value"
        var right = expressionProvider.GetValue(value);

        // x.Property == "Value"
        var comparisonExpression = expressionProvider
            .GetComparison(left, op, right);

        // x => x.Property == "Value"
        var lambdaExpression = ExpressionHelper
            .GetLambda<CategoryDto, bool>(obj, comparisonExpression);
        var q = _service.GetAll();

        var query = q.CallWhere(lambdaExpression);

        var list = query.ToList();

        return Ok(list);
    }

It works fine. because there is no filtering on child collection and results are filtering properly.





not setting value of only those field whose name is given list in java

I have class with 20 fields, and list with field names in it. I dont want to set field value who's name is in list.

Example -

Class Student { Name School DOB }

List -[ 'School']

so my function should set/update only Name and DOB as School is mention in list.





mercredi 24 janvier 2018

Build Object definition at compile time from string

I'm working on building generic API's where we need to have class objects as configurable so that any changes doesnt require actual code deployment to servers.

for instance, I need class object as below:

Public class Person{
public string  Name{get;set;}
public string  Id{get;set;}
}

I wan to define this structure in Database in string and while application running i will read the above definition from DB and built it and create an instance of it and assign values to the object.

is this possible?? I have been reading about Reflector but what i understand is we can create an instance of existing class dynamically but I need definition itself to built at run time.

what we are trying to achieve: we are building an API where consumers can pass their complex data objects to our system and we perform some validation on their data objects using LINQ Lambda expression and DynamicInvoke for that I need to have c# type object.I'm trying to avoid our application deployment if consumer want to do changes in the input object.





CDI: best way to get Class object from subclass

Imagine having the following class in a JEE project using a CDI container:

abstract class C <Implementer extends C> { ... }

What is the best way of getting a Class<Implementer> object to use in C?

I imagine something along the lines of using a producer and injecting it with @Inject Class<Implementer> impl;

Any ideas are appreciated.





Semantic Versioning Upgrade Validation Tool

I'm designing an application that checks to see if 3rd party modules will break when we release a software update (using semantic versioning). I've done quite a bit of research on call graphs and reflection but haven't been able to come up with a good solution. The code is written in PHP and Javascript and relies heavily on dependency injection and plugins. Is anyone familiar with a library out there that can perform this analysis? If not, what would be the best strategy to take in developing my own?

I wanted to create a static analysis tool but due to the interception and dynamic dependencies I think profiling might be the best option.





How do I create a delegate for a property getter from an open generic type

I have a PropertyInfo for a property on an open generic type, obtained in the following way:

public interface ITest<T>
{
    T Item { get; }
}

var propertyInfo = typeof(ITest<>).GetProperty("Item");

I'd like to be able to create a concrete, callable delegate, filling in the class type parameter (e.g. Func<ITest<int>, int>) from propertyInfo.

The obvious thing to try is propertyInfo.GetMethod.MakeGenericMethod(typeof(int)).CreateDelegate(...), but this fails because GetMethod isn't generic - it's a property on a generic class.

Is there a way to create this delegate, or can it only come about by using typeof(ITest<int>) to start with?





No default member found for type '' when using Activator.Instance - VB.NET

I'm writing a project where this will be extended with further modules later on, and as such i want as much of the code as possible to be independent, so i'm using various methods to keep everything as generic as possible, and not require hard-coding lists of types, classes etc.

As a Proof of concept, I've come up with the following code in a class;

Public Class clsAddition

Public Function DoAction(Value1 As String, Value2 As String) As String
    Dim dblTmpRet As Double
    Dim strTmpRet As String = ""

    If IsNumeric(Value1) = False Then strTmpRet += "Argument 'Value1' is not numeric. "
    If IsNumeric(Value2) = False Then strTmpRet += "Argument 'Value2' is not numeric. "

    If strTmpRet = "" Then
        dblTmpRet = CDbl(Value1) + CDbl(Value2)
        strTmpRet = CStr(dblTmpRet)
    End If

    Return strTmpRet

End Function

Private Function IsNumeric(Input As String) As Boolean
    Dim blnTmpRet As Boolean
    Try
        Dim dblTest As Double = CDbl(Input)
        blnTmpRet = True
    Catch ex As Exception
        blnTmpRet = False
    End Try
    Return blnTmpRet
End Function

Public Sub New()
    MyBase.New()
End Sub

End Class

And the following code in a windows form;

Private objObjectClass As Object
Private Sub cmdCreateObject_Click(sender As Object, e As EventArgs) Handles cmdCreateObject.Click

    Dim assem As Assembly = GetType(Form1).Assembly

    Dim typChosen As Type
    Try
        typChosen = assem.GetType(Me.comObjectType.SelectedItem.ToString, True)
    Catch ex As Exception
        typChosen = Nothing
    End Try

    If Not IsNothing(typChosen) Then
        'found it

        objObjectClass = Activator.CreateInstance(typChosen, True)()

    Else
        'didn't find it
        Throw New Exception("Unable to locate type in assembly")
    End If


End Sub

The issue is, that on the "Activator.CreateInstance(typChosen, True)()" line, the following error is thrown

An unhandled exception of type 'System.MissingMemberException' occurred in Microsoft.VisualBasic.dll Additional information: No default member found for type 'clsAddition'.

The aim is for me to be able to create instances of classes, then call a known name function on them. In this example, I'd create another class called "Divide", or another one that was called "Concatinate" etc, however in the real program these classes will all perform very different actions, have different properties, methods etc, with this one function ("DoAction" in the above example) sharing a syntax and return type.

Please help! been banging my head on this for a while now!

TIA!





mardi 23 janvier 2018

Java reflection - Get actual type of T in a generic interface

How do I get the actual type of T in a generic interface?

Given the following class:

class myClazz {
        private final IGenericInterface<?> genericInterface;

        myClazz(final IGenericInterface<otherClazz> genericInterface){
            this.genericInterface = genericInterface;
        }
}

How do I get the simple name of otherClazz out of the constructor using reflection?

I tried the following:

String otherClazzString = myClazz.class.getConstructors()[0].getParameterTypes()[0].toString(); // 

but I do not know what to do next to obtain the simple name of the actual type used in the generic interface.





C# PropertyInfo SetValue and Array

int size = Convert.ToInt32(sizeAttribute.Value);
Array newArray =  Array.CreateInstance(fieldType.GetElementType(), size);
PropertyInfo info = component.GetType().GetProperty(fieldNameAttribute.Value, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
var r = Convert.ChangeType(newArray, fieldType);
info.SetValue(component, r);

is there a way to let the array be filled with nulls.

Right now the line info.SetValue(component, r); is returning this error :

{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.





Reflection : Accessing nested bean property using java.beans.Expression

Background : I am using below snipet of code in my java application which can be used to get values of a field/property inside a class.

public static Object getProperty(Object object, String propertyName) {
    Object value;
    Expression expression = new Expression(object, "get" + StringUtils.capitalize(propertyName), new Object[0]);
    try {
        expression.execute();
        value = expression.getValue();
    } catch (Exception e) {
        value = null;
    }
    return value;
}

Now Refer this design

public class EntityA extends ParentEntity{
private String fieldA;
private String fieldB;
//Getters and Setters of above fields
} 

public class ParentEntity {
private String fieldC;
private GrandParentEntity grandParentEntity;

//Getters and Setters of above fields
}

public class GrandParentEntity extends SuperParentEntity{
private String fieldE;
private String fieldF;
//Getters and Setters of above fields
}  

Problem : Using above design scenario, what should I pass in my static method getProperty to access fieldE and fieldF (from GrandParentEntity using EntityA )

Note : I tried to pass

getProperty(new EntityA(),"grandParentEntity.fieldE")

but it gives error : java.lang.NoSuchMethodException: <unbound>=EntityA.getGrandParentEntity.fieldE();





Get channel from reflect.SelectCase

If I create an array of reflect.SelectCase

for i := range workers {
        cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(channels[i])}
}

Inside function like this:

func (cases []reflect.SelectCase){
    for i := range workers {
        cases[i].getChan <- struct{}{} // ??
    }
}

How can I get chan to send value?





Static reflection of member functions of non-POD classes

IIUC, nowadays one can easily do static reflection of POD classes/structs using, e.g., boost::hana or magic_get.

How can I perform similar static reflection of some member functions of non-POD classes? (I'm looking for a solution which doesn't require using a compiler fork which implements proposed static reflection extensions.)

In my specific use case, I have existing classes each having some setters. I'd like to wrap those classes with an adapter which pulls values of the appropriate types from some input generators and calls the matching setters on the adapted instance.

class A {
public:
   void setParam1(double); // To be annotated, e.g. REFLECT_MEM_FUNC(void setParam1(double);)
   void setParam2(Param);  // To be annotated, e.g. REFLECT_MEM_FUNC(void setParam2(Param);)
   void anotherFunc();     // Not annotated

private:
   double param1;
   Param param2;
// ...
};

class B {
public:
   void mySetParam(int);   // To be annotated, e.g. REFLECT_MEM_FUNC(void mySetParam(int);)

private:
   SomeOtherClass inner;   // parameter passed on to this member
// ...
};

template<
   typename AdaptedT, 
   // Tuple of references to classes, each implementing AppropriateParam get();
   // AppropriateParam return type of each getter must match the matching reflected setter.
   // To be clear, it's the instantiator's responsibility to provide matching Inputs; Inputs is not an auto-generated type since it can be anything providing the expected static interface.
   typename Inputs
> class Adapter {
public:
   Adapter(AdaptedT, Inputs);

   // Calls adapted's reflected setters with the values provided by inputs.
   setParametersFromInputs();

private:
   AdaptedT adapted;
   Inputs inputs;
// ... 
};

// Just to demonstrate the static interface expected from an input
template<typename ParamT>
class Input {
public:
   ParamT get();
// ...
};

Input<double> inputDouble { /* ... */ };
Input<Param>  inputParam { /* ... */ };
Adapted<A, std::tuple<Input<double>&, Input<Param>&>> adapter {
   { /* ... */ },
   {inputDouble, inputParam}
};

// Calls:
// adapted.setParam1(std::get<0>(inputs).get());
// adapted.setParam2(std::get<1>(inputs).get());
adapter.setParametersFromInputs();





Java reflection giving wrong concrete type at runtime

I'm trying to get the field value of an object using java.lang.reflect.Field#get. Moreover, I'd like to get the concrete type of a field of type interface java.util.List.

This is the code I'm currently using:

Field field = getField(klass, fieldName); 
//getField returns a field of type interface java.util.List
field.setAccessible(true);
Object result = field.get(target);

The problem is that instead of obtaining an Object instance of class java.util.Arrays$ArrayList (I'm 100% sure that this is the concrete type), I'm getting an instance of class java.util.ArrayList.

Am I doing something wrong? Thanks in advance.





Set all bool property values of an object

Consider the following object

public class Foo
{
    public bool RecordExist { get; set; }

    public bool HasDamage { get; set; }

    public bool FirstCheckCompleted { get; set; }

    public bool SecondCheckCompleted { get; set; }

    //10 more bool properties plus other properties
}

Now what I am trying to achieve is set the property value to true to all the bool properties apart from RecordExist and HasDamage. To achieve this I have gone ahead and created the following method.

public T SetBoolPropertyValueOfObject<T>(string[] propNames, Type propertyType, object value)
{
   PropertyInfo[] properties = typeof(T).GetProperties();

   T obj = (T)Activator.CreateInstance(typeof(T));

    if(propNames.Length > 0 || propNames != null)
        foreach (var property in properties)
         foreach (string pName in propNames)
            if (property.PropertyType == propertyType && property.Name != pName)
                 property.SetValue(obj, value, null);

        return obj;
}

The above method is then called as follows:

public Foo Foo()
{
   string[] propsToExclude = new string[]
   {
      "RecordExist",
      "HasDamage"
   };

    var foo = SetBoolPropertyValueOfObject<Foo>(propsToExclude, typeof(bool), true);

    return foo;
}

The method does not work as expected. When inside the foreach loop first time the RecordExist prop is set to false but when it goes into the loop again RecordExist is set to true and the rest of the props are set to true as well including HasDamage.

Can someone tell me where I am going wrong please.





GetValue reflection on iterating through collections and get item.ToString()

Inside Class:

public HashSet<string> Test = new HashSet<string>();
public List<string> Test2 = new HashSet<string>();
public String Test3 = "lol";

Getting all properties with reflection:

var properties = class.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Now I want to iterate through the collection properties only:

if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string))
{
    var valueString = string.Empty;
    foreach (var item in (IEnumerable)value)
    {
        valueString += item.ToString() + " | ";
    }
}

Works fine. Except when the collection is empty I get the collection fullname on item.ToString() instead of nothing / string.empty. Any way to fix that?





PHP Reflection class newInstance exit on execution

I'm writing controller testing unit with Fuelphp framework. And inside the code I'm trying to request application controller like this one :

$response = Request::force('controller_name/controller_method')->set_method('GET')->execute();

But this code unexpectedly exits the entire testing unit like PHP exit function. After trying to figure out what happened inside the core source code, I found out that in line 440 of https://github.com/fuel/core/blob/1.9/develop/classes/request.php forces the program to exit without any exception.

$this->controller_instance = $class->newInstance($this);

And before this code

$class = new \ReflectionClass($this->controller)

I'm using PHP 5.6.33 and Fuelphp 1.7.2 in my machine and I hope someone can help me with this error.





lundi 22 janvier 2018

how to intantiate Call instance using reflection

I am trying to send a DTMF tone in an incoming call. For that there is a method playDtmfTone in android.telecom.Call. As it is final class I am unable to create it's object directly.

That is why I am using reflection to get an object. but it throws an exception. Here is my code:

try{
    Class<?> c = Class.forName("android.telecom.Call");
    Object instance = c.newInstance();
    Method m = c.getDeclaredMethod("playDtmfTone", char.class);
    m.setAccessible(true);
    m.invoke(instance, new Object[]{'1'});
}catch (Exception e){
    Log.d("Exception of Reflection", e.getLocalizedMessage());
}

I am getting following msg:

Exception of Reflection: java.lang.Class has no zero argument constructor

I used this idea from this answer.

I am not sure what is going wrong.





Java annotation could not be found on class if it's the last one

Consider the following code:

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

import lombok.extern.log4j.Log4j2;
import net.jcip.annotations.Immutable;
import org.springframework.stereotype.Component;

// @CustomAnnotation("MyClass") // here the annotation is presented
@Component
@Log4j
@Immutable
// @CustomAnnotation("MyClass") // here the annotation is not presented
public class MyClass {
}

I'm listing out the annotation for MyClass:

MyClass myClass = new MyClass();
if (myClass.getClass() // this gives back the original class, not a proxy
        .getAnnotations()
        .stream()
        .filter(a -> a.getName().contains("My"))
        .anyMatch()) {
    System.out.println("found");
} else {
    System.out.println("not found");
}

  • If I put my annotation in the very first place (or so far it seems that before the @Component annotation, it's presented in the list.
  • If I put it the very last place (or at least after the @Component annotation, it's not presented.

I'm suspecting that something is going on with Spring in this case, but I'm really curious about the root cause.





Using Reflection to call AsQueryable() on a MongoDB Collection

I am building an OData service for MongoDB and have needed to steer away from using BsonDocuments and so I am trying to use reflection to call the AsQueryable() method on a MongoCollection. I have the below code:

    var method_info = typeof(IMongoDatabase).GetMethod("GetCollection");
    var method_ref = method_info.MakeGenericMethod(typeof(BaseDoc));

    var collection = method_ref.Invoke(database, new object[] { "docs", null });

    var method = typeof(IMongoCollectionExtensions).GetMethod("AsQueryable");
    var col_queryable_ref = method.MakeGenericMethod(typeof(BaseDoc));

NOTE: I have used a known type here called BaseDoc but that'll later be replaced with an emitted type via reflection

The above will all run without an error - but it hits a snag when I run

    dynamic res = col_queryable_ref.Invoke(collection, new object[] { collection, null }) as IMongoQueryable;
    return Ok(res);

While 'res' looks OK on debug inspection (not that I know what I am looking for), passing it back as a result will just generate an HTTP 406 error - so I clearly am not calling a working AsQueryable() method. If anyone has a way to call this using reflection that'd be very much appreciated!





Creating an instance using reflection with varying constructor parameters

I'm attempting to create an instance of a class at run time within my Kotlin program using reflection. However, the type and number of constructor arguments will vary. Is there a way of implementing a solution to plan ahead for unknown constructors?

Thanks





Adding Alpha to my Refraction Shader in Unity

I'm new to shaders but I've been following some tutorials and I tried a LOT of things on this particular shader... to no avail.

I used the MirrorReflection4 (Link to the Shader) and I wanna add a alpha which I can control from outside because and also maybe to add a texture to tell the Reflection where on a plane it is allowed to make reflection.

Would be Awesome if somebody could help a amateur :)

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "FX/MirrorReflection"
{
        Properties
        {
        _MainTex("Base (RGB)", 2D) = "white" {}
        //_ReflectionAlpha("ReflectionAlpha", Range(0, 1)) = 0
        [HideInInspector] _ReflectionTex("", 2D) = "white" {}
        }
                SubShader
        {
                Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
                ZWrite Off
                Blend SrcAlpha OneMinusSrcAlpha
                LOD 1024

                Pass{
                CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
                struct v2f
        {
                float2 uv : TEXCOORD0;
                float4 refl : TEXCOORD1;
                float4 pos : SV_POSITION;
        };
        float4 _MainTex_ST;
        v2f vert(float4 pos : POSITION, float2 uv : TEXCOORD0)
        {
                v2f o;
                o.pos = UnityObjectToClipPos(pos);
                o.uv = TRANSFORM_TEX(uv, _MainTex);
                o.refl = ComputeScreenPos(o.pos);
                return o;
        }
        sampler2D _MainTex;
        sampler2D _ReflectionTex;
        fixed4 frag(v2f i) : SV_Target
        {
                fixed4 tex = tex2D(_MainTex, i.uv);
        fixed4 refl = tex2Dproj(_ReflectionTex, UNITY_PROJ_COORD(i.refl));
        return tex * refl;
        }
                ENDCG
        }
        }
}




Fill array(value of a field) with the elements of a List

I have a field of an array type, which should be set/filled to an array containing the elements of a list of the same type. So far I tried out:

  • to create an Object array and fill it with the elements of the list
  • cast the fields value to an Object array and fill its values

    //the generic type of List is the fields type without the array
    if(field.getType().isArray() && obj instanceof List) {          
        List<?> list = (List<?>) obj;
        Object[] array = new Object[list.size()];
    
        for(int x = 0; x < array.length; x++) {
            array[x] = list.get(x);
        }
    
        obj = field.getType().cast(array);
    }
    
    field.set(module, obj);
    
    

but everything leads to a ClassCastException: [D cannot be cast to [Ljava.lang.Object;
My question is: Is it possible to fill the array of the field with the elements of the List? If yes how?





Check type of member/property

Let's say i have any class, like this one:

class SomeClass(val aThing: String, val otherThing: Double)

Then I use reflection to analyze the fields of this class:

 for(field in SomeClass.declaredMemberProperties){

    }

How can I check the type of each field?





Check type of member/property

Let's say i have any class, like this one:

class SomeClass(val aThing: String, val otherThing: Double)

Then I use reflection to analyze the fields of this class:

 for(field in SomeClass.declaredMemberProperties){

    }

How can I check the type of each field?





Check type of member/property

Let's say i have any class, like this one:

class SomeClass(val aThing: String, val otherThing: Double)

Then I use reflection to analyze the fields of this class:

 for(field in SomeClass.declaredMemberProperties){

    }

How can I check the type of each field?





Check type of member/property

Let's say i have any class, like this one:

class SomeClass(val aThing: String, val otherThing: Double)

Then I use reflection to analyze the fields of this class:

 for(field in SomeClass.declaredMemberProperties){

    }

How can I check the type of each field?





Error Group by string column name (run time column name)

I am encountering errro in q.GroupBy method in below code It Says :

     Cannot implicitly convert type 
     'System.Linq.IQueryableg<System.Linq.IGrouping<TRet, TModel>>' to 
     'System.Linq.IQueryable<TModel>

Above is error thrown

    public static IQueryable<TModel> GroupByDynamic<TModel>(this IQueryable<TModel> q, string name)
    {
        Type entityType = typeof(TModel);
        PropertyInfo p = entityType.GetProperty(name);
        MethodInfo m = typeof(QueryableHelper).GetMethod("GroupByProperty").MakeGenericMethod(entityType, p.PropertyType);          
        return (IQueryable<TModel>)m.Invoke(null, new object[] { q, p });
    }


    public static IQueryable<TModel> GroupByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)  
    {
        ParameterExpression pe = Expression.Parameter(typeof(TModel));
        Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
        return q.GroupBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
    }

Belwo code q.OrderBy Working without any issue

   public static IQueryable<TModel> OrderByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
    {
        ParameterExpression pe = Expression.Parameter(typeof(TModel));
        Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
        return q.OrderBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
    }





is it possible to extract a class from an assembly created with Reflection.Emit and save it physically to a directory?

I would like to use this manipulation to generate projects dynamically with specific content (Classes, Methods ...).

So, Is there a way to save dynamic classes with code without need for an external tool to decompile them?

Thanks for your attention. I’m looking forward to your reply.





is it possible to get generic class by given parameter?

Assume i have "java.util.List<java.lang.String>" as a parameter in String. I want to get it as Class or Type, something like that:

ClassLoader cl=Thread.currentThread().getContextClassLoader();
Class clazz=cl.loadClass("java.util.List<java.lang.String>");

Is it possible somehow?





What is the point of OOP visibility in PHP when Closures and Reflections are available?

Consider this code here:

final class TinkerWithMe {
    protected $key1 = 19;
    private $key2 = 88;
}

$class = new TinkerWithMe();

$getKeys = function() {
    return array($this->key1, $this->key2);
};

$oldKeys = $getKeys->call($class);

$newKey1 = 96;
$newKey2 = 42;

$setKeys = function() use ($newKey1, $newKey2) {
    $this->key1 = $newKey1;
    $this->key2 = $newKey2;
};

$setKeys->call($class);

Why bother with OOP visibility when you can get around it so easily with Closures or Reflections?

Is there a way of blocking this kind of thing that I am missing?





dimanche 21 janvier 2018

How to register Callback of Interface using Relfection? Android

I have an interface:

package com.testing.server;

public interface OnViewFoundListener{
     void onViewFound(String msg);
}

And the Class that registers Listeners

   public class FindViewUtil {
               private static final List<OnViewFoundListener> 
       mOnViewFoundListeners = new ArrayList<>();

      public static void addViewListener(OnViewFoundListener onViewFoundListener) 
      {
        mOnViewFoundListeners.add(onViewFoundListener);
      }

     public static void notifyViewRendered() {
         mOnViewFoundListeners.get(0).onViewFound("Hello World");
     } 

    }

I want to be able to register using the addViewListener function and listen for OnViewFoundListener's onViewFound callbacks via Reflection. How can I achieve this goal ?





Java Reflections - invoke method with BigInteger argument

I need to invoke methods in a class (called Foo in this example) using only Strings. For example passing BigInteger class as argument is not an option in my case.

My code works fine, when I use java.lang.String, but if try with other types, like BigInteger for example a "java.lang.IllegalArgumentException: argument type mismatch" is thrown

This is the class I am testing the reflection against:

package com.test;

import java.math.BigInteger;

public class Foo {

    private String name;

    private BigInteger age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigInteger getAge() {
        return age;
    }

    public void setAge(BigInteger age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Foo [name=" + name + ", age=" + age + "]";
    }
}

My goal is to invoke setAge(BigInteger age) method using Java reflections. This is the code I use:

package com.main;

import java.lang.reflect.Method;

public class Run {

    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.test.Foo");
            Object obj = clazz.newInstance();
            Method m = clazz.getMethod("setAge", new Class[] 
{Class.forName("java.math.BigInteger")});
            m.invoke(obj, "12");
            System.out.println("after method call " + obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Unfortunately after executing the code I get the java.lang.IllegalArgumentException.

To summarize my question: haw can I use arguments different than Strings using java reflections, given the type itself should be provided as String?





samedi 20 janvier 2018

Java generics and reflection to create and set model for SimpleJdbcCall in Spring

I am trying to use reflection and generics to create models using SimpleJdbcCall, so that I won't have to create a distinct mapper per model.

Here is my implementation so far:

public abstract class DAO<T extends ModelBase> {

    private final DataSource dataSource;

    DAO(final DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected List<T> buildModels(SqlParameterSource sqlSource, Class modelBase) {
        final String RESULT_SET = "RESULT_SET";
        return (List<T>)new SimpleJdbcCall(dataSource)
            .withCatalogName("someCatalog")
            .withSchemaName("someSchema")
            .withProcedureName(getProcForModel(modelBase))
            .returningResultSet(RESULT_SET, (ResultSet rs, int rowNum) -> {
                /*
                1. get actual instance of modelBase that is passed in
                2. get reference to the setters of the modelBase instance
                   or be able to pick out where to set things in the constructor
                3. loop thru ResultSet, setting parameters on model where the name of the
                   setter or constructor arg matches the name of the column in the resultSet
                */
            }).execute(sqlSource).get(RESULT_SET);
    }

}

The issues I have enumerated above at the things that I have not been able to figure out how I am supposed to do using the Reflection API in Java. Does anyone know how to do what I am trying to achieve?

Also, some of the values coming from the resultSet might not be Strings, but rather things like Dates and boolean. How would I reflectively call the right method on the resultSet? i.e. getInts() or getDate() or getBoolean(), etc.





Cannot cast java.lang.Integer to int [duplicate]

This question already has an answer here:

I'm confused by the following Java code, in which I try to use two methods to cast an Object to an int:

Object o = 1;
System.out.println((int) o);
Class <?> t = int.class;
System.out.println(t.cast(o));

The second line casts the Object to an int traditionally, and succeeds. The fourth, however, which I would expect to be functionally equivalent, throws

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Integer to int

What's the functional difference between the second line and the fourth? Why would one fail while the other succeeds?





EF Core 2.0: Determine which PropertyInfos of a generic TEntity are primary keys via reflection

I am writing a MySQL INSERT ... ON DUPLICATE KEY UPDATE implementation via a raw SQL command in EF Core 2.0. I am very close to a working solution, but the only problem that I have is determining which PropertyInfos read via reflection are primary keys. In the CreateUpdates() method below, I need to filter primary keys out from columnProperties so they are not a part of the update SQL statement. Can anyone suggest a method for doing this?

I have tried using EntityFramework.PrimaryKey , but I can't seem to get it to work with generics (TEntity).

I have included all of my relevant code, but the piece I am focused on in this question is the TODO in the last method, CreateUpdates(). Full source code is here. Thanks for any suggestions!

private static void InsertOnDuplicateKeyUpdate<TEntity>(DbContext dbContext) where TEntity : class
{
    var columnProperties = GetColumnPropertiesLessBaseEntityTimestamps<TEntity>();
    var tableName = GetTableName<TEntity>();
    var columns = string.Join(", ", columnProperties.Select(x => x.Name));
    var values = CreateValues<TEntity>(columnProperties);
    var updates = CreateUpdates(columnProperties);
    var rawSqlString = "INSERT INTO " + tableName + " (" + columns + ") VALUES " + values +
                        " ON DUPLICATE KEY UPDATE " + updates;
    dbContext.Set<TEntity>().FromSql(rawSqlString);
    dbContext.SaveChanges();
}

private static string GetTableName<TEntity>()
{
    return typeof(TEntity).Name.Pluralize().ToLower();
}

private static List<PropertyInfo> GetColumnPropertiesLessBaseEntityTimestamps<TEntity>()
{
    return typeof(TEntity).GetProperties().Where(x =>
        x.PropertyType.Namespace != "System.Collections.Generic" &&
        !new List<string> {"CreatedDateUtc", "ModifiedDateUtc"}.Contains(x.Name)).ToList();
}

private static string CreateValues<TEntity>(IReadOnlyCollection<PropertyInfo> columnProperties)
{
    return GetSeedRows<TEntity>().Select(row => CreateRowValues(columnProperties, row)).Aggregate("",
        (current, rowValues) => current == "" ? rowValues : current + ", " + rowValues);
}

private static string CreateRowValues<TEntity>(IEnumerable<PropertyInfo> columnProperties, TEntity row)
{
    return (from property in columnProperties
                let value = row.GetType().GetProperty(property.Name).GetValue(row)
                select WrapStringPropertyValueInSingleQuotes(property, value)).Aggregate("",
                (current, value) => current == "" ? "(" + value : current + ", " + value) + ")";
}

private static object WrapStringPropertyValueInSingleQuotes(PropertyInfo property, object value)
{
    if (property.PropertyType == typeof(string))
        value = "'" + value + "'";
    return value;
}

private static string CreateUpdates(IEnumerable<PropertyInfo> columnProperties)
{
    //TODO: filter keys out
    return columnProperties.Select(property => property.Name).Aggregate("", (current, column) => current == ""
        ? column + " = VALUES(" + column + ")"
        : current + ", " + column + " = VALUES(" + column + ")");
}





vendredi 19 janvier 2018

Find object with variable amount of attributes (one or more) from a hashmap

Lets say we have person class :

class Person{
long id;
String username;
String password
String firstName;
String lastName;
String address;
String phoneNumber;

// setters and getters..
}

And we have a hashmap full of objects of type person hashMap<String,Person> with string being the object's username.

I want to way to search for the object with specified attributes (one or more), FOR EXAMPLE :

username:jim54 and address:UK

or

firstName: Jimmy with last name : tornabone and address :Poland

or

those who lives in UK ( address :UK )

Without writing ton of overloaded methods..

my method uses reflection to find the mutators of a single attribute :

 Method getter=getDeclaredMethodIgnoreCase(Person.class,"get"+"attribute"); 
 Method setter=getDeclaredMethodIgnoreCase(Person.class,"set"+"attribute");

then compares and changes





Invoke Equals method on Enum property on class

I have the following setup:

public enum TestEnum
{
    Item1,
    Item2,
    Item3,
    Item4,
    Item5
}

public class Test
{
    public TestEnum TestEn { get; set; }
}

I now what to get the equals method and invoke it:

        var equalsMethod = typeof(TestEnum).GetMethod("Equals");

        Test g = new Test()
        {
            TestEn = TestEnum.Item3
        };

        var r1 = equalsMethod.Invoke(g, new object[] { TestEnum.Item3 });
        var r2 = equalsMethod.Invoke(g, new object[] { 2 });
        var r3 = equalsMethod.Invoke(g, new object[] { (TestEnum)2 });

        var r4 = g.TestEn.Equals(TestEnum.Item3);
        var r5 = g.TestEn.Equals((TestEnum)2);

Using reflection and the invoke call r1, r2 and r3 lines all fail with the following error:

Object does not match the target type.

What can I add to make this work?

I'm effectively looking at doing the same as lines r4 and r5 but using reflection.

Thanks





Dynamically populate specific generic properties of a mock object with a specific subclass of the same generic type with Moq

I'm trying to create a generic class that can build a Mock of a generic interface to assist me with various unit testing functions.

I need the built mock object to have all its DbSet<T> properties populated with TestDbSet<T> instances (TestDbSet<T> inherits from DbSet<T>).

For a specific example, given the interface:

public interface IAppointmentSchedulerContext
{
    DbSet<ServiceCenter> ServiceCenters { get; set; }
}

I would like to be able to have my TestDbContextBuilder class construct a mock instance where the ServiceCenters property is populated with an instance of a ServiceCenter<T>.

This is what I have so far:

public class TestDbContextBuilder<TDbContextInterface> where TDbContextInterface : class
{
    public TDbContextInterface Build()
    {
        var mock = new Mock<TDbContextInterface>();
        var dbSetProps = typeof(TDbContextInterface).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                    .Where(pi => pi.PropertyType.IsGenericType &&
                                                                 pi.PropertyType.GetGenericTypeDefinition() ==
                                                                 typeof(DbSet<>));

        //populate all the DbSet<TEntity> properties (in dbSetProps) on the mock with TestDbSet<TEntity> instances

        return mock.Object;
    }
}

If I were doing this statically, outside of the generic builder, I would just do this:

mock.SetupProperty(m=>m.ServiceCenters).Returns(new TestDbSet<ServiceCenter>());

But how do this dynamically, for all the DbSet<> properties on the generic TDbContextInterface interface?





Get all properties on a class that are a specific open generic type

If I have the following generic class:

public class Gen<T>
{
    public T Value { get; set; }
}

And a class that uses it:

public class Thing
{
    public Gen<int> GenIntProperty { get; set; }
    public Gen<string> GenStringProperty { get; set; }
    public string NoGenericProp { get; set; }
}

Using reflection, how can I get just the properties that are based on the open generic type Gen<T>, specifically GenIntProperty and GenStringProperty?

I've tried various forms of this code, but I keep running in to errors like this due to not being able to reference the open generic type.

Using the generic type 'UserQuery.Gen' requires 1 type arguments

var genProps = typeof(Thing).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(pi => pi.PropertyType == typeof(Gen));





Initializing all property lists in constructor with reflection c#

I am trying to initialize all properties in class (lists) with using reflection:

public class EntitiesContainer
{
    public IEnumerable<Address> Addresses { get; set; }
    public IEnumerable<Person> People { get; set; }
    public IEnumerable<Contract> Contracts { get; set; }

    public EntitiesContainer()
    {
        var propertyInfo = this.GetType().GetProperties();
        foreach (var property in propertyInfo)
        {
            property.SetValue(property, Activator.CreateInstance(property.GetType()), null);
        }
    }
}

I am getting exception:

No constructor has been defined for this object without parameters.

I would appreciate tips.





How to change a property getter at runtime in C#

I have a class with a property that looks like this:

public class Hmd{
    Transform HmdTransform{
        get{ device.GetTransform(); }
    }
}

device.GetTransform() gets the Transform from a driver.

Now I want to change the get method of the property at runtime, to something like:

public class Hmd{
    private Transform hmdTransform;
    Transform HmdTransform{
        get{ return hmdTransform; }
    }
}

Is there any way to do that? I would have to create a new member and change the getter. If I can't create a new member could I just change the device.GetTransform() line? I assume I would have to use Reflection.Emit?

Additional complication: All of this is in Unity, so I can only use Mono.





Reflect on Clojure Function Name

How do I use reflection in Clojure to extract the function name of a symbol that evaluates to a function?

(require '[clojure.reflect :as r])
(defn foo [x] x)
(r/reflect foo)
=> {#clojure.reflect.Field ... 'gobbledygook}

Something about (map :name (:members (r/reflect foo)))?





jeudi 18 janvier 2018

Get value of a non-public member of sender object

I'm trying to use reflection and all the examples I've seen says this should work. I'm trying to get the PortName property as shown here.

This returns null:

var port = this.GetType().GetProperty("PortName", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty);

enter image description here





Get Properties of object within list

I am doing some dynamic form work based on properties within an object(creating a datagridview to populate the object). Everything works great until I have a List<>, and I get a Capacity and Count property but not the proper properties of said object.

dynamic ObjectToPopulate;
PropertyInfo[] PopulatedObjectProperties = ObjectToPopulate.GetType().GetProperties();

Any help is always appreciated.





Java Reflection: the fast way to retrieve value from property

I would like to use the fastest way to retrieve value from a property.

Should I use:

public Object getValue(Object obj, Field field) {
    field.setAccessible(true);
    return field.get(obj);
}

or should I use:

public Object getValue(Object obj, Field field) throws Exception {
    StringBuilder methodName = new StringBuilder();
    methodName.append("get");
    methodName.append(field.getName().substring(0, 1).toUpperCase());
    methodName.append(field.getName().substring(1, field.getName().length()));
    for (Method method : methods) {
        if (method.getName().equals(methodName.toString())) {
            return method.invoke(obj);
        }
    }
}

or should I use:

public Object getValue(Object obj, Field field) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        StringBuilder methodName = new StringBuilder();
        methodName.append("get");
        methodName.append(field.getName().substring(0, 1).toUpperCase());
        methodName.append(field.getName().substring(1, field.getName().length()));
        for (Method method : methods) {
            if (method.getName().equals(methodName.toString())) {
                MethodHandle mh = lookup.findVirtual(obj.getClass(), methodName.toString(), MethodType.methodType(field.getType()));

                return mh.invoke(obj);
            }
        }
    }

Thanks in advance.





mercredi 17 janvier 2018

ProjectEuler 202

Three mirrors are arranged in the shape of an equilateral triangle, with their reflective surfaces pointing inwards. There is an infinitesimal gap at each vertex of the triangle through which a laser beam may pass.

Label the vertices A, B and C. There are 2 ways in which a laser beam may enter vertex C, bounce off 11 surfaces, then exit through the same vertex: one way is shown below; the other is the reverse of that. see the image here Image

There are 80840 ways in which a laser beam may enter vertex C, bounce off 1000001 surfaces, then exit through the same vertex.

In how many ways can a laser beam enter at vertex C, bounce off 12017639147 surfaces, then exit through the same vertex?

  
     import fractions
     surf = 12017639147
     row = (surf + 3)/2
     offset = 3 - (row %3)
     col = offset
     row -= offset
     total = 0
     while row > col:
       if fractions.gcd(row,col) == 1:
          total += 1
       row -= 3
       col += 3
       if row %1000000 == 0:
         print (total)
     print (total * 2)
  

This solution is taking a long time.How to do it in lesser time?





How to use DOMCatalogParser?

I am trying to parse an XML catalog file using the following code:

  ByteArrayInputStream bais = ... // loading xml from a file        
  DOMCatalogReader r = new DOMCatalogReader();
  String targetClass = "MyCatalogParser";

  r.setCatalogParser(null, "catalog", targetClass);
  Catalog catalog = new Catalog();
  InputStream is = bais;
  r.readCatalog(catalog, is); // line 73

MyCatalogParser is my custom DOMCatalogParser class:

import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.readers.DOMCatalogParser;

public class MyCatalogParser implements DOMCatalogParser {

    @Override
    public void parseCatalogEntry(Catalog catalog, Node node) {
        System.out.println("test");
    }

}

The XML I am trying to parse is the following:

<?xml version="1.0"?>
<catalog >
  <group  prefer="public"  xml:base="a" >
    <public 
       publicId="b"
       uri="docbook45/docbookx.dtd"/>

    <system
       systemId="c"
       uri="docbook45/docbookx.dtd"/>

    <system
       systemId="d"
       uri="docbook45/docbookx.dtd"/>
  </group>
</catalog>

I use the following Java version:

$ java -version
openjdk version "1.8.0_151"

Unfortunately I get the following exception:

Exception in thread "main" com.sun.org.apache.xml.internal.resolver.CatalogException: Catalog Exception 6
    at com.sun.org.apache.xml.internal.resolver.readers.DOMCatalogReader.readCatalog(DOMCatalogReader.java:202)
    at Main.main(Main.java:73)

Digging a bit further, I found out that for some reason MyCatalogParser cannot be loaded:

try {
  domParser = (DOMCatalogParser) ReflectUtil.forName(domParserClass).newInstance();
} catch (ClassNotFoundException cnfe) {
  catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
  throw new CatalogException(CatalogException.UNPARSEABLE);

It seems like the classloader does not find the application class MyCatalogParser.

I tried to look for other implementations of DOMCatalogParser but did not find any in the JDK nor on the Internet.

Is there a way to make this work knowing that the classloader cannot load any application class extending DOMCatalogParser and that there are no implementation of DOMCatalogParser in the JDK?





C# dynamic compiling - statically referencing compiler class

I've made a voxel based VR game in Unity, and am trying to move some of my code to external files that I can compile at run-time. This will allow users to modify game files that are externally based, without me needing to give them access to all of my source code.

A guy named exodrifter shared a tutorial on how to do this (see here) which I have been essentially able to drag and drop into my project. The one issue is that I cannot reference the class I am using to compile the code in my dynamic code.

I get a NullReferenceException when trying to compile

 Debug.Log(BlockInstantiator.GetBlockType(100))

Compiling happens from the function Compile within the class BlockInstantiator.

The compiling function:

public Assembly Compile(string source)
    {
        var provider = new CSharpCodeProvider();
        var param = new CompilerParameters();

        // Add ALL of the assembly references
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            param.ReferencedAssemblies.Add(assembly.Location);
        }

        // Add specific assembly references
        //param.ReferencedAssemblies.Add("System.dll");
        //param.ReferencedAssemblies.Add("CSharp.dll");
        //param.ReferencedAssemblies.Add("UnityEngines.dll");

        // Generate a dll in memory
        param.GenerateExecutable = false;
        param.GenerateInMemory = true;

        // Compile the source
        var result = provider.CompileAssemblyFromSource(param, source);

        if (result.Errors.Count > 0)
        {
            var msg = new StringBuilder();
            foreach (CompilerError error in result.Errors)
            {
                msg.AppendFormat("Error ({0}): {1}\n",
                    error.ErrorNumber, error.ErrorText);
            }
            throw new Exception(msg.ToString());
        }

        // Return the assembly
        return result.CompiledAssembly;
    }

A bit of googling suggests that I need to include the EntryAssembly in my referenced assemblies, but when I access this using

Assembly.GetEntryAssembly()

I get a null reference - as documented here

Also trying to get the entry assembly through other means as answered here has so far been unsuccessful. Are there any alternative ways for me to get around this problem?

Apologies for the long post, Thanks in advance.





how could change a local variable in another method in java?

how could change the method "change" that "java" print? I mean there is anyway to change local variable "x" for main method in method "change"? reflection can help or another way needed?how?

public static void main(String[] args) {

    String x = new String("abc");
    change(x);
    System.out.println(x); //output = abc
}

public static void change(String x) {
    x="java";
}





C# reflection and finding all references of a Class/Property in my project solution

I have a class named Test and I instantiated that class in several other classes. Is there any way I could find all references to the Class "Fix" programmatically. I know I could find that with Find All References in VisualStudio but I want to achieve this programmatically for my requirement. Any help, please.

Example: Fix.cs

namespace Testing
{
    public class Fix
    {
        public string fixName = "Name";
    }
}

CodeFix.cs

namespace Testing
{
    public class CodeFix
    {
        private string GetName()
        {
            Fix fix = new Fix();
            return fix.fixName;
        }
    }
}

Now I want to write code to Find All References to a variable "fixName" in my solution (namespace Testing). Is there any way I could achieve this programmatically either for a class or for a variable. I would like to get the result with the fileName and variable referenced code line.

Example:

Result
{
FileName="CodeFix.cs",
Line=return fix.fixName;
}

I am supposed to automate the below scenario for which I need Find All References. I should not use public fields, so When I find a public field like "fixName" I should change the fixName from public to private and then expose the same using a property.

private string fixName;
public string FixName
{
    get { return fixName; }
    set { fixName = value; }
}

so I should change the file codeFix.cs - line return fix.fixName;must be changed with the property name return fix.FixName;.

I have a VSIX project to fix code violation, I need to implement this "automated fix" to avoid using public fields. By any chance Is there a way to get the Visual Studio -> Find All References data?





How to get the base constructor calling parameters with C# Reflection

How to get the hard-coded parameter that the sub-class constructor is used to call the base-class constructor?

public class BaseMessage
{
    public BaseMessage(string format, params string[] parameteres)
    {
    }
}

public class HelloMessage : BaseMessage
{
    public HelloMessage(string name) : base("Hello {0}", name)
    {
    }
}

public class IntroductionMessage : BaseMessage
{
    public IntroductionMessage(string name, string myName) : base("Hello {0}, I am {1}", name, myName)
    {
    }
}

I would like to get all the hard-coded formatting string for the sub-classes of BaseMessage, i.e. "Hello {0}" and "Hello {0}, I am {1}"





mardi 16 janvier 2018

Why isAnnotationPresent return false when loading a class from another jar

I am trying to figure out what I am doing wrong.

I have implemented two custom annotation stored in main jar file and in other jar some test classes marked with this annotations.

The idea is load classes from other jar files which match with certain criteria ( my custom annotations in this case)

I can load the classes and get the Annotations with getAnnotations().

But using the method isAnnotationPresent not. Always return false;

I would like to know how to fix this.

Thanks

The Annotations code

package reflectordemo.interfaces;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SortAlgorithm {}

The demo jar lib code. Note: Reflectordemo is the main jar file and is referenced at compile time

package ppk.classes;

import reflectordemo.interfaces.*;

@SortAlgorithm
@ClassDescription(text = "Bubble sort algorithm")
public class BubbleSort
{
}

@SortAlgorithm
@ClassDescription(text = "Quick sort algorithm")
public class QuickSort
{        
}

public class NaiveSort { }

The Loader class

package reflectordemo;

import java.io.FileInputStream;
import java.util.jar.JarInputStream;
import java.util.jar.JarEntry;
import java.lang.annotation.Annotation;

import java.lang.Class;
import java.lang.ClassLoader;
import java.net.URLClassLoader;
import java.net.URL;
import java.io.File;

import reflectordemo.interfaces.*;

public final class Reflector
{

 public static void Listclasses(String file)
 {
 try
 {

 JarEntry current;
 String currentname;
 File curfile = new File(file);

 try 
 (
 FileInputStream stream = new FileInputStream(file);
 JarInputStream j = new JarInputStream(stream);
 URLClassLoader cl = URLClassLoader.newInstance(new URL[] {curfile.toURL()},ClassLoader.getSystemClassLoader())

 )
 {
 while ( (current = j.getNextJarEntry()) != null ) 
 {

 if ( current.getName().endsWith(".class") ) 
 { 

 currentname = current.getName().replace(".class","");
 String classname = currentname.replace('/', '.');
 System.out.println(currentname); 

 Class w = cl.loadClass(classname);

 //Annotation[] ans = w.getAnnotations();

 if ( w.isAnnotationPresent(SortAlgorithm.class) == true )
 {
 System.out.println(classname + " has SortAlgorithm Annotation");
 }
 else
 {
 System.out.println(classname + " Not match with criteria");
 } 
 } 
 }
 } 
 }
 catch(Exception e)
 { 
 System.out.println(e.getMessage());
 } 
 } 
}





Hook to function without delegates (Reflection)

Is there a way I could use reflection to hook one function to another without using delegates?

class A
{
    Foo()
    {
    }
}

class B
{
    Func()
    {
    }
}

Is there a way to call Func after Foo was called without using events, delegates or just calling Func from inside Foo? I'm using this for the UI in a Unity game I'm making and I don't want to add a bunch of events to my classes just for UI, this seems a messy way to do it (I think most people do it this way but I don't like it).





Java reflections method get another method with annotation

I am using Cucumber with Selenide for my UI tests and I have these methods

public static void initPage(String pageName) throws Exception {
    Set<Class<?>> annotated = new Reflections(PAGES_PACKAGE).getTypesAnnotatedWith(PageTitle.class);

    for (Class classToInit : annotated) {
        PageTitle annotation = (PageTitle) classToInit.getAnnotation(PageTitle.class);
        if (annotation.name().equals(pageName)) {
            classToInit.newInstance();
            lastInitialized = substringAfter(classToInit.toString(), "class ");
            lastInitClass = classToInit;
            return;
        }
    }

    throw new AutotestError("Could not find page to init: " + pageName);
}

public static SelenideElement findElementByTitle(String elementName) throws IllegalAccessException, InstantiationException {
    Set<Field> annotated = new Reflections(lastInitialized, new FieldAnnotationsScanner()).getFieldsAnnotatedWith(ElementTitle.class);

    for (Field field : annotated) {
        ElementTitle annotation = field.getAnnotation(ElementTitle.class);
        if (annotation.name().equals(elementName)) {
            field.setAccessible(true);
            SelenideElement el = (SelenideElement) field
            return el;
        }
    }
    throw new AutotestError("Element not found: " + elementName);
}

I am very new to reflections and am trying to build a page objects pattern utilising the org.reflections.Reflections library to search for annotated fields in various page object classes. I am, however, having problems returning the SelenideElement from the field I'm getting in the second method (line SelenideElement el = ... is plain wrong at the moment). How do I get the field I can use as a SelenideElement (with @ElementTitle and @FindBy annotations) in my test? Thanks in advance.





java: ERROR: "cannot find symbol – class Constructor" when making instance from String, with parameters

I searched through all the questions here that involve 'reflection' to instantiate a parameterised object using a String of the class name, but I cannot get it to work because Java doesn't recognise Constructor as a class.

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

Class[] types = {Double.TYPE, String.TYPE};
Constructor constructor = myClass.getConstructor(types);

Object[] parameters = {1.0, "hello"};
Object instanceOfMyClass = constructor.newInstance(parameters);

This is the code I tried using, I also tried writing the parameters differently, but those are irrelevant to the problem (please reply to the Constructor class issue). How do I make this work?





Type.GetType() doesn't find dynamically created type

I'm creating types dynamically by using Reflection.Emit. When I try to resolve a type created that way, I either get a return value of null or an error is thrown, that the type couldn't be found.

I've tried to use search like this:

Type.GetType("MyNamespace.MyType, FullQualifiedAssemblyName", false);

Is there anything special to have a look on? Perhaps even through the process of creation?

Thanks in advance.





lundi 15 janvier 2018

Can an anonymous inner class, created by an abstract enclosing class, determine the implementing class via reflection?

The short form of the question is:

  • abstract class A1
  • abstract class A2 that creates an anonymous inner A1
  • Class A3 extends A2 - can an instance of A1 created by A2 know it was created within A3?

Fleshing out the question:

Lets say i have an abstract class:

public abstract class Abstract1 {}

Then I have a second abstract class that can create instances of Abstract1:

public abstract class Abstract2 {
    protected Abstract1 createAbstract1() {
        return new Abstract1() {};
    }
} 

Third, I have a concrete implementation of Abstract2:

public class Concrete extends Abstract2 {} 

Lets put some print statements into Abstract2:

public abstract class Abstract2 {
    public Abstract1 createAbstract1() {
        System.out.println("I am: " + getClass().getName());
        Abstract1 a1 = new Abstract1() {};
        System.out.println("A1 is enclosed by: " + ab1.getClass().getEnclosingClass().getName());
        return a1;
    }
} 

When we construct Concrete and ask for an A1 as follows...

Concrete charlie = new Concrete();
Abstract1 myA1 = charlie.createAbstract1();

...we see the following output:

I am: Concrete
A1 is enclosed by: Abstract2

How can myA1 know it was created by a Concrete instead of an Abstract2?