Java FasterXml(Jackson) Mixins and Inheritance - mixins

There are two simple calsses
public class A { private int propId; public int getPropId(){return this.propId;} }
public class B extends A { }
and two mixins
public interface AMixin{ #JsonProperty("propIdA") int getPropId();}
public interface BMixin{ #JsonProperty("propIdB") int getPropId();}
jsonObjectMapper = new ObjectMapper();
// register mixin
jsonObjectMapper.addMixIn(B.class, BMixin.class);
jsonObjectMapper.addMixIn(A.class, AMixin.class);
The following two calls get the same results:
jsonObjectMapper.writeValue(writer, new A());
jsonObjectMapper.writeValue(writer, new B());
but i expect propIdA for first and propIdB for second one.

Related

How can I easily implement an interface with a single property that implements that interface?

public interface IStuff
{
public int A { get; }
public event EventHandler StuffHappened;
}
public class Stuff : IStuff
{
public int A { get; private set; }
public event EventHandler StuffHappened;
}
public class WorkerA : IStuff
{
Stuff stuff = new();
public int A => stuff.A;
public event EventHandler StuffHappened
{
add => stuff.StuffHappened += value;
remove => stuff.StuffHappened -= value;
}
}
public class WorkerB : IStuff
{
// same as WorkerA
}
public class WorkerC : IStuff
{
// same as WorkerA
}
If I have several classes that need to implement the same interface in the same way, but they can't inherit the same base class (perhaps they are already inheriting something else), is there a way to write a helper class that implements the interface and just have that as a property in the several classes that need to implement the interface and have those classes implement the interface by wrapping the helper class WITHOUT having to wrap every single property of the helper class? Wrapping events is especially the worst! I find myself in this situation so often that it's worth my time to write this post. Thanks

Autofac - One interface, multiple implementations

Single interface: IDoSomething {...}
Two classes implement that interface:
ClassA : IDoSomething {...}
ClassB : IDoSomething {...}
One class uses any of those classes.
public class DummyClass(IDoSomething doSomething) {...}
code without Autofac:
{
....
IDoSomething myProperty;
if (type == "A")
myProperty = new DummyClass (new ClassA());
else
myProperty = new DummyClass (new ClassB());
myProperty.CallSomeMethod();
....
}
Is it possible to implement something like that using Autofac?
Thanks in advance,
What you are looking for is, as I remember, the Strategy Pattern. You may have N implementations of a single interface. As long you register them all, Autofac or any other DI framework should provide them all.
One of the options would be to create a declaration of the property with private setter or only getter inside Interface then implement that property in each of the class. In the class where you need to select the correct implementation, the constructor should have the parameter IEnumerable<ICommon>.
Autofac or any other DI frameworks should inject all possible implementation. After that, you could spin foreach and search for the desired property.
It may look something like this.
public interface ICommon{
string Identifier{get;}
void commonAction();
}
public class A: ICommon{
public string Identifier { get{return "ClassA";} }
public void commonAction()
{
Console.WriteLine("ClassA");
}
}
public class A: ICommon{
public string Identifier { get{return "ClassB";} }
public void commonAction()
{
Console.WriteLine("ClassA");
}
}
public class Action{
private IEnumerable<ICommon> _common;
public Action(IEnumerable<ICommon> common){
_common = common;
}
public void SelectorMethod(){
foreach(var classes in _common){
if(classes.Identifier == "ClassA"){
classes.commonAction();
}
}
}
}

MapStruct equivalent of hint(Dozer)?

In Dozer we are able to mention interfaces in hint during field mapping. How can we achieve the same in MapStruct ?
I could not put the exact code here. But, it is the similar as below.
We have here an Domain class example:
Class A<T extends B> extends C<T>
{
...
};
Where,
B is a abstract class.
C is a class which contains a List item which we have to map.
Similar is the structure of the classes and interfaces on DTO side.
So, the mapping is as below in Dozer:
<mapping>
<class-a>Domain.A</class-a>
<class-b>DTO.A</class-b>
<field>
<a>item</a>
<b>item</b>
<a-hint>Domain.B</a-hint>
<b-hint>DTO.B</b-hint>
</field>
</mapping>
In MapStruct how do we refer the interfaces as given in the hint in Dozer ?
Scenario:
We have:
public class ShopList<T extends Inp> extends Shop<T>\
{ ... };
where,
Inp is a abstract class with no fields in it like:
public abstract class Inp() { };
Shop is a class like:
public class Shop<T extends ShopInp> implements Serializbale
{ private List<T> items = new ArrayList<T>();
//getters and setters for the items };
ShopInp is a public interface with no fields in it like:
public interface ShopInp {} .
We have similar structure of classes on DTO side and Domain side.
Could you please let me know how would the mapper look like for the above scenario ?
In general, If we try mapping the ShopList class, then, how do we ensure that the T extends ShopInp and T extends Inp are also being mapped as a part of ShopList?
So called hints can be used via BeanMapping#resultType. MapStruct can use that to create the instance of the object you are trying to map. However, it will only create mapping for the elements of the abstract class, as it has no other information during compilation time (Dozer uses reflection and can detect the fields of the type during runtime).
Imagine you have this structure
public interface Fruit {
String getName();
String setName(String name);
}
public Apple implements Fruit {
...
}
public Banana implements Fruit {
...
}
public abstract class FruitDto {
private String name;
//getters and setters
}
public AppleDto extends FruitDto {
...
}
public BananaDto extends FruitDto {
...
}
public class Basket {
private Collection<Fruit> fruits;
}
public class BasketDto {
private Collection<FruitDto> fruits;
}
Your mapper can then look like:
#Mapper
public interface BasketMapper {
BasketDto map(Basket basket);
#BeanMapping(resultType = BananaDto.class)
FruitDto map(Fruit fruit);
}
Using this mapper all fruits in the BasketDto would be of an instance BananaDto (due to the BeanMapping#resultType and mapping would only be created for the elements of the FruitDto

Testing mocked objects rhino mocks

I am new to RhinoMocks, and I am trying to write a test as shown
I have classes like these
public class A
{
public void methodA(){}
}
public class B
{
public void methodB(A a)
{
a.methodA();
}
}
And i am trying to test it like this
A a = MockRepository.GenerateMock<A>();
public void ShouldTest()
{
B b = new B();
b.methodB(a);
a.AssertWasCalled(x=>x.methodA());
a.VerifyAllExpectations();
}
But it is giving the error as shown:
System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call.
How do I test methodB then?? Can someone help??
Rhino mock creates proxy class when you call MockRepository.Generate *** method. This means that it extends your type. If you don't declare any abstraction you cannot make any derivation which is essential in any mocking framework.
You can do two things
Create an interface (better design)
Make the member virtual (this will allow RhinoMocks to derive from your type and create a proxy for the virtual member
Sample code
public interface IA { void methodA();}
public class A:IA{public void methodA() { }}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
[TestFixture]
public class Bar
{
[Test]
public void BarTest()
{
//Arrange
var repo = MockRepository.GenerateMock<IA>();
//Act
B b = new B();
b.methodB(repo);
//Assert
repo.AssertWasCalled(a => a.methodA());
repo.VerifyAllExpectations();
}
}
You have concrete classes with no virtual methods and no interfaces. You can't mock anything.
Update:
Here's one way to do it:
public interface IA
{
void methodA();
}
public class A : IA
{
public void methodA(){}
}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
Then use
IA a = MockRepository.GenerateMock<IA>();

Cast a CustomList<CustomClass> to IList<Interface>

(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn't going to work out, because a FooList<FooClass> is not an IList<IFoo>. This is why:
var myList = new FooList<FooClass>();
IFoo obj = new SomeOtherFooClass();
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass
You need to either make a copy or use an interface that is actually covariant on the contained type, like IEnumerable<T> instead of IList<T>. Or, if appropriate, you should declare your FooList<FooClass> as an FooList<IFoo> from the get-go instead.
Here is a small implementation that demonstrates my second suggestion:
public interface IFoo { }
public class FooClass : IFoo { }
public class FooList<T> : IList<T>
{
public void RemoveAt(int index) { /* ... */ }
/* further boring implementation of IList<T> goes here */
}
public static void ListConsumer(IList<IFoo> foos)
{
foos.RemoveAt(0); // or whatever
}
public static IList<IFoo> ListProducer()
{
// FooList<FooClass> foos = new FooList<FooClass>(); // would not work
FooList<IFoo> foos = new FooList<IFoo>();
foos.Add(new FooClass());
return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool
}
public static void Demo()
{
ListConsumer(ListProducer()); // no problemo
}