auto mapping properties from two classes with third class using automapper - automapper

I have two classes, say ClassA and ClassB, and I want to map them with ClassC. How can I do it?
ClassA has only 1 property and ClassB has 5 properties. ClassC has 6 properties.
Situation is something as below:
Public ClassC MapRequest(classA id, ClassB someProperties){
_mapper.Map<ClassC>(id);
_mapper.Map<Classc>(someProperties);
retrun type of ClassC;
}

There is overload of Map method available.
var objClassC = _mapper.Map<ClassA, ClassC>(id);
// You need to pass above instance to next call.
_mapper.Map<ClassB, ClassC>(someProperties, objClassC );
Hope this helps.

Related

Nomin automap causes infinite loop

I am using Nomin for mapping tasks. As taken from the documentation of Nomin it should be able to map fields with the same name by itself in case automapping has been activated. When activating it, it causes an infinite loop exception.
I have the following:
mappingFor a: CoinsOnMarketPlace, b: Coin
// automap() // when deactivated it works fine, when activated infinite loop
a.coin.name = b.name
a.coin.rank = b.rank
a.priceUSD = b.priceUSD // Could be automapped
a.priceBTC = b.priceBTC // Could be automapped
...
Exception:
org.nomin.core.NominException: ./net/hemisoft/ccm/repository/coinmarketcap2coin.groovy: Recursive mapping rule a = b causes infinite loop!
One thing worth adding regarding your use case - this Recursive mapping rule a = b causes infinite loop! exception is thrown because you use groovy classes in your mapping rule. Nomin uses ReflectionIntrospector and what's important:
It performs getting/setting properties using accessor methods which are called through the Java reflection mechanism. ReflectionIntrospector uses supplied NamingPolicy instance to determine accessor methods. JbNamingPolicy is used by default, this implementation cerresponds the JavaBeans convention. Its InstanceCreator named ReflectionInstanceCreator instantiates objects using Class.newInstance().
Source: http://nomin.sourceforge.net/introspectors.html
A simple Groovy class like:
class Entity {
String name
String somethingElse
}
gets compiled to a Java class that implements GroovyObject providing following methods:
public interface GroovyObject {
Object invokeMethod(String var1, Object var2);
Object getProperty(String var1);
void setProperty(String var1, Object var2);
MetaClass getMetaClass();
void setMetaClass(MetaClass var1);
}
In this case ReflectionInstanceCreator combined with automap() resolves following mappings:
a.property = b.property
and
a = b
where a = b mapping comes from MetaClass getMetaClass() getter method I suppose, because there is no mapping like a.metaClass = b.metaClass resolved. a.property = b.property gets resolved because of Object getProperty(String var1) method.
Solution
This problem can be solved by specifying explicitly ExplodingIntrospector for your mapping script that:
It performs getting/setting properties using a class field immediately through through the Java reflection mechanism and may be useful in case when domain object don't provide accessors for their properties. Supplied instance creator is ReflectionInstanceCreator.
Source: http://nomin.sourceforge.net/introspectors.html
All you have to do is to add
introspector exploding
right below mappingFor a: ..., b: ... header. For example:
import mypackage.Entity
import mypackage.EntityDto
mappingFor a: Entity, b: EntityDto
introspector exploding
automap()
a.test2 = b.test1
Tested with two Groovy classes, worked like a charm. Hope it helps.

Spring data Cassandra polymorphism, override column definition

I'm creating a heirarchy of classes for the purposes of denormalizing a table. Tables are quite wide so to manage hassle and errors, I would like to declare all fields in the parent and then alter the definition of specific fields in the child. This way I can have a normal column in the parent be redefined as part of a primary key in the child.
E.g.:
Basic super-class
public class A {
#Column
protected int age;
}
Class extending A
#Table
public class B extends A {
#PrimaryKey
protected K key;
...
}
Primary key for A, with a new definition of the age column.
#PrimaryKeyClass
public class K {
#PrimaryKeyColumn
private int age;
#PrimaryKeyColumn
private int ignore;
}
That doesn't seem to work. I get a Multiple definition of identifier exception.
So far I can only declare fields that won't change in the parent and then declare all possibly-changing fields in each child. I don't like this because I have to know upfront every field that might become part of future primary keys.
Putting the annotations on the (parent) getters and overriding those doesn't seem to have done anything.
Any way to solve this aside from keeping only never-changing columns in the parent?
Putting the annotations on the (parent) getters and overriding those doesn't seem to have done anything.
Annotating the child getters with #Transient did!
So: annotate the parent getters rather than the fields, make child getters #Transient, move column definition into the key, done.
From here:
http://docs.datastax.com/en/developer/java-driver/3.1/manual/object_mapper/creating/
One powerful advantage of annotating getter methods is that annotations are inherited from overridden methods in superclasses and superinterfaces; in other words, if a getter method is overridden in a subclass, annotations in both method declarations will get merged together. If duplicated annotations are found during this merge process, the overriding method’s annotations will take precedence over the overridden’s.

C# Inheritance access confusion

public class ABC
{
}
public class DEF : ABC
{
}
public class Class1
{
ABC abc = new DEF(); //No error
DEF def = new ABC(); //Compile time error
}
Can anyone explain to me this scenario.
and under what circumstances we might use it.
Its because as per the OOD rule you can assign child to parent but you cannot assign parent to child.
//this possible as you re assigning child to parent
ABC abc = new DEF(); //No error
//this is illegal as you are trying to assign child to parent directly
DEF def = new ABC(); //Compile time error
Reconsider your design again or if you want to convert parent object to child than you need method for that conversion directly its not possible to do it as per OOD rules.
Consider real time example relation of Customer and RetailCustomer or Corporatecustomer of bank. Where you can easily say RetailCustomer or CorporateCustomer is Customer, but you cannot say Customer is RetailCustomer or CorporateCustomer because customer can be of any type.
Same goes for relation between Parent Shape Class and Child Rectangle,Circle etc. class.
This is called as Ploymorphism .
As explained in MSDN
At run time, objects of a derived class may be treated as objects of a
base class in places such as method parameters and collections or
arrays. When this occurs, the object's declared type is no longer
identical to its run-time type.
Base classes may define and implement virtual methods, and derived
classes can override them, which means they provide their own
definition and implementation. At run-time, when client code calls the
method, the CLR looks up the run-time type of the object, and invokes
that override of the virtual method. Thus in your source code you can
call a method on a base class, and cause a derived class's version of
the method to be executed.
The answer of for this question is best explained here MSDN Polymorphism
Let's say ABC is Person, while DEF is Student (which is a subclass of Person). You can always treat a Student as a Person, so the assignment to abc (of type Person) of a Student is correct, but you cannot treat a generic Person as Student, so the assignment to def is wrong (for instance, you cannot get the student number of a person which is not a student)

How to add java mock objects to hashset?

I want to create a set that holds mock java objects.Like the following
MyObject objectA = mock(MyObject.class);
when(objectA.getName()).thenReturn("nameA");
MyObject objectB = mock(MyObject.class);
when(objectB.getName()).thenReturn("nameB");
MyObject objectC = mock(MyObject.class);
when(objectC.getName()).thenReturn("nameC");
Set<MyObject> mySet = new HashSet<>();
mySet.add(objectA);
mySet.add(objectB);
mySet.add(objectC);
mySet.size();// this will be "1" instead of "3"
I want the size of the set to be "3" instead of "1".
I know that when adding an object to set it will verify hashcode of the object. In this case all of my mock objects have same hash code so the set is able to hold only one value.
I had also tried the following
int someRandomInt = 12345;
when(objectA.hashCode()).thenReturn(someRandomInt):
But Mockito fails to stub out private final methods.
How can I have a set that holds different mock objects ?
You can use IdentityHashMap class instead of HashSet. It uses reference comparison instead of equals methods so objects with different addresses will not be considered equal by this class.

Vala: Pass String as Class

Scenario:
I have x number of classes. Lets say 10; Each class does different UI Functions. When a user loads a file, that extension tells the program the classname to load; but it's in the form of a string.
Is there anyway to pass a string off as a classname? Something to the effect of.
var classname = "Booger";
var nose = new classname(){ //classname really means "Booger"
//Do Operation
}
You can reflect a type by name using var t = Type.from_name(classname);, however, this works on all types, including enums and structs and it might be the type Type.INVALID. You should probably do some checks, like t.is_a(typeof(MyParentClass)).
You can then instantiate a copy using var obj = Object.new(t);. The whole thing would look like:
var classname = "Booger";
var t = Type.from_name(classname);
if (t.is_a(typeof(MyParentClass)))
return Object.new(t);
else
return null;
It's also worth noting that the run-time type names have the namespace prepended, so you might want to do "MyNs" + classname. You can check in either the generated C or doing typeof(MyClass).name().
I've had the same problem as the OP in regards to getting an assertion error against null. If you take a look at the Glib documentation (in C) it mentions you have to register your class by actually specifying the class name first before you can actually use a string representation of your class name.
In other words you have to use your class first BEFORE you can instantiate a copy of your class with Glib.Type.from_name ("ClassName").
You can use your class first by instantiating a class instance or by getting type information for your class.
var type = typeof (MyClass);
var type_from_string = Type.from_name ("MyClass");
Furthermore, when you use Object.new to create a class there are two things you need to be aware of:
1) You need to cast the return value to get your specific class or base class.
var instance_of_my_class = Object.new (type) as MyClass;
2) Constructors for your class will no longer be called (I don't why). You will need to use the GObject style constructor inside your class:
construct {
pizza = 5;
}

Resources