How to properly instantiate a Thrift/Scrooge generated class in Scala - scala

I would like to instantiate a crooge generated class (or trait, better said).
Now since I can't instantiate a trait, I used a anonymous wrapper class to generate some test object I want to serealize:
val err = new ClientError{}
But I cannot set any properties to this object (or at least I don't know how).
What's the proper way to do this?
The background is I want to create an object, serialize it, send it, deserialize it and check if it worked, if the sample has the same properties.
Thanks for any help!

There is an object ClientError, with an apply method.
Just do
val err = ClientError(whatever, fields, your, thrift, struct, has)

Related

Using Swift reflection to initialize a general class object with data. Cant iterate through properties

I have noticed a class where the coding key for a new property was not added to a Codable object. As a result, data was silently getting dropped. I would like for this to never happen again.
The goal is to write a more general unit test for any object that is Codable that does the following.
Create an instance of the object with "random" data
Encode the object
Decode the object and see if it is equal to the original object
Thus far I have tried Mirror(reflecting: ClassName.self). The goal is that I could essentially go through each property and come up for a way to generally initialize it with random data. The problem is its children object is not particularly useful. Its a very weird object that does not even loop like a collection as I have seen in some example code.
Curious then if it is even possible to initialize an object with random data in its fields using Swift reflection. A lot of the example code for doing on this rely on the object being set up properly with Encode/Decode which is an assumption I cannot take.

Pass a class name as string argument to create instance

Is there any possible way to pass a class name/path as String argument to call it in code in runtime?
Im working with some legacy code and i have no way to change it globally. Creating new integration to it suggest me to create new copy of class X, rename it, and pass new instance of Y i have created manually. My mind tells me to pass Y as some kind of argument and never copy X again.
I don't quite understand why you (think that) you need to do what you are trying to do (why copy class in the first place rather than just using it? why pass classname around instead of the class itself?), but, yeah, you can instantiate classes by (fully qualified) name using reflection.
First you get a handle to the class itself:
val clazz = Class.forName("foo.bar.X")
Then, if constructor does not need any arguments, you can just do
val instance = clazz.newInstance
If you need to pass arguments to constructor, it gets a bit more complicated.
val constructor = clazz.getConstructors().find { c =>
c.getParameters().map(_.getParameterizedType) == args.map(_.getClass)
}.getOrElse (throw new Exception("No suitable constructor found")
// or if you know for sure there will be only one constructor,
// could just do clazz.getConnstructors.headOption.getOrElse(...)
val instance = constructor.newInstance(args)
Note though, that the resulting instance is of type Object (AnyRef), so there isn't much you can actually do with it without casting to some interface type your class is known to implement.
Let me just say it again: it is very likely not the best way to achieve what you are actually trying to do. If you open another question and describe your actual problem (not the solution to it you are trying to implement), you might get more helpful answers.

Scala Argument Capture of External Class

So I want to check arguments that I send to an external class that I do not control. The external class is assumed tested, I simply want to test if I passed it the right parameters. I have tried some combination of ArgumentCaptor etc, but not much luck
import org.ABC.ExternalClass
case class Foo(i:Int, j: Int...) {
val EC = CreateExternalClass()
def CreateExternalClass(): ExternalClass = {
new ExternalClass (i, j, ....many parameters)
}
}
I think you are getting things wrong here: you can only use an ArgumentCaptor on calls to mocked objects. You can't use them to "intercept" arbitrary calls between all kinds of objects.
Meaning: you could only use an ArgumentCaptor if you would be using a mocked ExternalClass object. But then you would not need to capture, as you probably could do simply method call argument verification.
But of course, you can't use Mockito to mock that call to new in your production class. The options you have:
Turn to PowerMockito or JMockit; frameworks that allow to mock calls to new. Not recommended.
Rework your production code to not do that call to new. Probably not helpful here; as this class might already be a wrapper around that external class
Go for checking on the created object: check if you could use getter methods to simply query the newly created object to have the values that you expect to show up inside

In Scala, how would I give a Singleton a constructor?

My design incorporates a small database abstraction, whereby I implement each database as a Singleton (well, an object), with custom methods on the database for the couple of operations the code calls (it's mainly a log parser, dumping interesting statistics to a database).
I'd like to construct the Singleton database classes if possible, such that at runtime, each is constructed with config values (and those values remain constant for the remainder of the program's runtime). This would allow me to better test the code too (as I can mock the databases using Mockito or some such).
I'm still only learning Scala, but it seems there's no way to attach a constructor to a Singleton, and would appreciate any input on this problem - is there a better way to do what I'm doing? Is there some preferred way of constructing a Singleton?
Cheers in advance for any help.
Just put the constructor code in the body of the object definition:
object Foo {
println("Hello") // This will print hello the first time
// the Foo object is accessed (and only
// that once).
}
Rather than use a singleton (which is hard to test).. Whoever's creating the actors could create a database session factory and pass it to each actor, then it's still shared... and testable.
Not sure if this if this is what you're looking for but as the article explains, use the apply method without extending the base class
case class Foo(name:String)
object Foo { def apply(name:String) = new Foo(name) }
enter link description here

How do you set the class of an object to something else?

I've seen this recently and now I can't find it …
How do you set the class of an object to something else?
--Update: Well, in Pharo! Like:
d:=Object new. d setClass: Dictionary.
Only that it isn't actually setClass. How can you modify the class pointer of an object?
There is #primitiveChangeClassTo:.
It requires that both original and target class have the same class layout. For some strange reason it expects an instance of the target class as parameter, which is however not used.
So you would do
d := Object new.
d primitiveChangeClassTo: Dictionary new.
however this fails, since dictionaries have two instance variables but plain objects have none.
If you are into meta-programming, you might also be interesting in using any object as a class. I used that in Protalk to realize a prototype based language that works directly on top of Smalltalk.
The method #setClass: is used in some specific contexts and with different implementations (Check it with the Method Finder).
Object has some helpers to conver the current object in other sort of, as for example #asOrderedCollection, because this last permit the operation:
asOrderedCollection
"Answer an OrderedCollection with the receiver as its only element."
^ OrderedCollection with: self
HTH.
ok, then you can try something as:
d := Object new.
e := Dictionary new.
d become: e.
But, please, try #become: with caution, because in lot of situations it break the image.
Take a look at Class ClassBuilder. It creates the a new class, when you modify a class, and then switches the instances of the former to instances of the later. Therefor it should provide some method that does, what you ask for.