mercredi 3 mars 2021

How to I output the name of an input?

For example, if I have char character = a, how would I be able to print out it's name, which is "character", along with it's output within a single printf? I know I can do printf("character = %c", character);, but how can I still print out the input's name if I enter char something = b and make it print out "something = b" instead of "character = b"?





SWIFT reflect all implementations of a certain protocol

I want to use SWIFT reflection to resolve all implementations of a certain protocol.

The problem I'm trying to solve is that I want to test all present and future implementations of a certain protocol.

The reflection in SWIFT is limited, but after reading up on it, I believe it should be possible. I have found the following articles on reflection in SWIFT, but I am having trouble mapping it in to my specific use case.

https://nshipster.com/mirror/ https://www.swiftbysundell.com/articles/reflection-in-swift/

How can I resolve and iterate over all implementations of a specific protocol?

protocol Animal {
    var color: UIColor { get }
    var name: String { get }
}

class Cat: Animal {
    var color: UIColor = .red
    var name: String = "Joshua"
}

class Dog: Animal {
    var color: UIColor = .blue
    var name: String = "Anna"
}

class Animals {
    var animalCollection: [Animal]
    
    init() {
        ...
    }
}

class TestAnimals {
    func testAnimalCollection() {
        let mirror = Mirror(reflecting: Animals.self)

        for child in mirror.children {
            print(child.value)
        }
    }
}




How to use newInstance() ? JAVA

Im trying to use newInstance in different ways but I cant figure out which is the right one.

Child c = new Child();
Constructor[] ctors = c.getClass().getDeclaredConstructors();
Constructor ctor = ctors[0];

// I tried this:
Child c = (Child)ctor.newInstance(); // just to see if newInstance would work, but nothing

I did this (above) to get my constructor, but I already tried this as I saw in some posts:

c.getClass().getDeclaredConstructors().newInstance();

Which is the right way to use newInstance? Im very confused about this.





How to get classes declared in the top level python file

Is there a simple way to retrieve all the classes declared in the top-level python file?

For example :

import inspect                                                                                                          
                                                                                                                                                                                                                                               
class FirstClass:                                                                                                       
    pass                                                                                                                
                                                                                                                         
class SecondClass:                                                                                                      
    pass                                                                                                                
                                                                                                                        
if __name__ == '__main__':                                                                                              
    print(inspect.getmembers(__name__))

I was trying to print FirstClass and SecondClass.

I've tried with inspect module without a success as shown before

I've tried with dir() however it stops working when it is called inside a function.

print(dir())

will result: ['FirstClass', 'SecondClass', 'annotations', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec', 'inspect']

The list contains the classes I'am looking for.However when it is called inside another scope like function the result is different.

def getdir():
   print(dir())

it will print an empty list





mardi 2 mars 2021

How to validate properties via reflection after each user input on console application

I am requesting user input based on the properties I am grabbing which are all strings. Where User contains name, lastname, email, etc.

I wanted to input value to Person and validate per line. So if the user enters first property incorrectly, a validation error will print out.

Person p = new Person();

foreach(PropertyInfo pi in p.GetType().GetProperties())
{
    Console.WriteLine($"Enter {pi.Name}");
    string input = Console.ReadLine();
                
}

Below, I can check one by one, just figuring out how I can incorporate this to add for above.

RegistrationValidation rv = new RegistrationValidation();

p.FirstName = "";
p.Email = "";
p.LastName = "";
            
ValidationResult results = rv.Validate(p);

if (results.IsValid == false)
{
   foreach (ValidationFailure failure in results.Errors)
    {
       System.Console.WriteLine($"{failure.PropertyName}: {failure.ErrorMessage}");
    }
}




Java reflection - get primitive class value from java variable

I am trying to execute methods of a class using reflection, the method accepts a map of methodNames & list of arguments the method needs. One such method is setPaperSize(int x). Now the problem is at the //error line, x.getClass() returns Integer not int, and due to that I end up with NoSuchMethodException. I know this returns runtime class of variables, Any workarounds or solutions to make it work?

private void applyProps(HTML2PDF converter, Map<String, Object> propValues) {
        propValues.keySet().forEach(k -> {
            Method methodToExecute;
            try {
                Object argObj = propValues.get(k);
                List<Object> args = null;
                if(argObj instanceof List) {
                    args = (List<Object>)argObj;
                }else {
                    args = new ArrayList<Object>();
                    args.add(argObj);
                }               
//error line
                List<Class<?>> argsClass =  args.stream().map(x -> x.getClass()).collect(Collectors.toList());
                methodToExecute = HTML2PDF.class.getMethod(k, argsClass.toArray(new Class[argsClass.size()]));              
                methodToExecute.invoke(converter, args);
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException("Error in invoking the reflection method", e);
            }
        });
    }




Replace template Placeholder with Object Properties with Reflection

In C#, I want to replace the string Placeholder with Object Properties using Reflection

        string formula = "{\"Name\": \"\", \"Email\": \"\" }";
        Student student = new Student();
        student.Name = "Parker";
        student.Email = "Parker@xyz.com";
        student.Address = "Mark Avenue";
        var result1 = GenerateJson(formula, student);
        //Output :  "{\"Name\": \"Parker\", \"Email\": \"Parker@xyz.com\" }"

        student.Name = "Royal";
        student.Email = "Royal@xyz.com";
        student.Address = "Cross Lane";
        var result2 = GenerateJson(formula, student);
        //Output :  "{\"Name\": \"Royal\", \"Email\": \"Royal@xyz.com\" }"





    public string GenerateJson(string formula, Student student)
    {
        string result = "";
        //logic for replacing the Placeholder woth object properties
        return result;
    }

    class Student
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }

    }