How to get class name in a method inside this class - qore

Is there any method how to get class name inside a method in the same class? Or in general, if I have an instance of a class and I need to know which class is it instance of?

In Qore (according to the tag on the question), you need to use the <object>::className() pseudo-method on your object.
ex:
prompt% qore -nX '(new Mutex()).className()'
"Mutex"
If you are in the class, use this pseudo-method on the automatic self variable:
prompt% qore -ne '
class T {
string getClassName() {
return self.className();
}
}
class U inherits T {}
printf("%s\n", (new U()).getClassName());
'
U
Alternatively you can also use the get_class_name() function as in the following example:
prompt% qore -nX 'get_class_name(new Mutex())'
"Mutex"
Note that if a class defines a method with the same name as a pseudo-method, the class method will be called instead, and the pseudo-method cannot be called, in which case you have to use the function mentioned above.

Please see http://php.net/manual/pl/function.get-class.php.
get_class($this);

Related

Creating a new instance of a KClass

I have a Kotlin class whose primary (and only) constructor is empty.
I have a reference to this class:
val kClass: KClass<MyClass> = MyClass::class
How do I create an instance of this class using reflection?
In Java I would do myClass.newInstance() but it seems in Kotlin I need to find the constructor first:
kClass.constructors.first().call()
I have seen mention of primaryConstructor in some bug reports but it's not showing up in my IDE.
In your case, Java reflection might be enough: you can use MyClass::class.java and create a new instance in the same way as you would with Java reflection (see #IngoKegel's answer).
But in case there's more than one constructor and you really need to get the primary one (not the default no-arg one), use the primaryConstructor extension function of a KClass<T>. It is a part of Kotlin reflection, which is not shipped within kotlin-stdlib.
To use it, you have to add kotlin-reflect as a dependency, e.g. a in Gradle project:
dependencies {
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}
Assuming that there is ext.kotlin_version, otherwise replace $kotlin_version with the version you use.
Then you will be able to use primaryConstructor, for example:
fun <T : Any> construct(kClass: KClass<T>): T? {
val ctor = kClass.primaryConstructor
return if (ctor != null && ctor.parameters.isEmpty())
ctor.call() else
null
}
You can use the Java class to create new instance:
MyClass::class.java.newInstance()
For those checking this question now, since Kotlin 1.1 there's also createInstance() extension method on KClass
Much like the accepted answer, this function works only in case class has an empty constructor or constructor with all default arguments.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect.full/create-instance.html
Expanding on Alexeys Answer, to include a primary constructor call with parameters:
/* Example class with no-args constructor */
class MyClass
/* Example class requiring parameters */
class MyClassWithParams(parameter1: String, parameter2: MyClass)
val myKClass: KClass<MyClass> = MyClass::class
val myKClassWithParameters: KClass<MyClassWithParams> = MyClassWithParams::class
/* We can create an object by calling createInstance when no constructor parameters are required as explained in other answers. */
val myObject: MyClass = myKClass.createInstance()
/* To create an object with parameters, we need to get the constructor first, and call it with the parameters instead, similarly to how we would do in Java. */
val myObjectWithParameters: MyClassWithParams? =
myKClassWithParameters.primaryConstructor?.call(
"StringParameter", myObject
)

Kotlin: How can a child class use a parent's extension function in the super constructor call?

How can a child class use its parent's extension function in a lambda field?
Consider this parent class:
abstract class Parent(val field: Int.() -> Any) {
fun Int.print() = println(this)
}
And this child:
class Child : Parent({
print() // DOESN'T COMPILE
this.print() // DOESN'T COMPILE
5.print() // DOESN'T COMPILE
val value = 5
value.print() // DOESN'T COMPILE
})
The reason why you cannot use Parent's extension inside Child super constructor call argument is that its Parent part is not initialized yet at that point and thus cannot be used as dispatch receiver of the extension.
Member extension functions can use the eclosing class' members and this means that they need an instance of the class to be called with, and you cannot use the instance in its own constructor arguments.
Otherwise, you can use Parent's extensions anywhere inside the Child members and in constructors (or init blocks), because super constructor is called before own constructors:
class Child : Parent {
constructor(): super({}) {
5.print()
}
fun f() {
5.print()
}
val g: (Int) -> Unit = { it.print() }
}
In your example the lambda in question is not a field of Parent (strictly speaking), but a parameter to a function (class constructor).
The lambda is constructed (resolved) before any object, Child or Parent, is created. That's why methods can be resolved and the lambda is not in the scope of Child.
PS
The name of the topic suggests the following situation, but it compiles all right:
class Child : Parent({}) {
val lambdaField: Int.() -> Any = {
print()
this.print()
5.print()
}
}

Jackson custom deserializer module to abstract class

I have a big set of classes (like more that 100) and they are all extend from some abstract class, let's call it ParentClass. Let's call child classes ChildA,ChildB, etc. How can I register custom deserializer for all children and get class type inside my Deserializer?
I tried:
module.addDeserializer(ParentClass.class, new MyObjectDeserializer());
but it does not work.
I want to skip doing (what is working):
module.addDeserializer(ChildA.class, new MyObjectDeserializer(ChildA.class));
module.addDeserializer(ChildB.class, new MyObjectDeserializer(ChildB.class));
module.addDeserializer(ChildC.class, new MyObjectDeserializer(ChildC.class));
//etc......
Class type should be known, as I am use Jackson for spring #RequestBody method, what have defined class name there.
Any ideas how this can be done?
As far as I know, I don't think there is a mechanism in jackson that will address your exact needs.
However, there are a couple alternatives you can try.
Deserializing polymorphic types with Jackson describes one such alternative, however, you would still need to explicitly define all of the supported subtypes.
Another alternative that would not require you to explicitly define deserialization relationships would be to change your class hierarchy from one of inheritance to that of a container.
For example, converting your abstract parent class to a container like so:
public class DataContainer<T> {
String commonString;
Integer commonInteger;
T subData;
}
Would allow you to simply define in your controller input function as
public String controllerFunction(DataContainer<ClassA> classA);
without a need to define all these subclass deserializations.
Late to the party but I had a similar problem which I solved by registering a custom Deserializers to my SimpleModule. The code is in Kotlin but it should be easy to port it to Java.
The class itself:
class UseBaseClassSimpleDeserializers(
private val baseClass: Class<*>,
private val baseClassDeserializer: JsonDeserializer<*>
) : SimpleDeserializers() {
#Throws(JsonMappingException::class)
override fun findBeanDeserializer(
type: JavaType?,
config: DeserializationConfig?,
beanDesc: BeanDescription?
): JsonDeserializer<*>? {
val beanDeserializer = super.findBeanDeserializer(type, config, beanDesc)
return if (beanDeserializer == null && baseClass.isAssignableFrom(type!!.rawClass)) {
baseClassDeserializer
} else {
beanDeserializer
}
}
}
How to register the custom Deserializers class to a SimpleModule:
val simpleModule = SimpleModule()
simpleModule.setDeserializers(UseBaseClassSimpleDeserializers(ParentClass::class.java, ParentClassDeserializer()))

Variable is not of the type class

I have a custom class for holding a collection of data.
I use this class throughout my code, and it works without a hitch, except for in one place, when I need to pass the class object to a method. Here is some very basic code to demonstrate what I am seeing.
public class doSomething
static void myMethod(customClass_myItem) {}
public class customClass
public str classMethod() {}
form method
customClass myItem = new customClass();
myItem.classMethod(); //this works, so I know the class is good
doSomething::myMethod(myItem); //Gives error: variable is not of the type CLASS.
I am completely lost here. If I couldn't use the class at all, I would understand, but with it not working when passed to another method.. doesn't make any sense. If I put in a breakpoint, the debugger indicates myItem is a class of the correct type.
Any suggestions?
Thanks
Your myMethod expects an object of class customClass_myItem (or a descendant) not customClass.
If you change your parameter type to object it should work.
static void myMethod(Object o) {}

Using reflection in PHPUnit

I'm testing a private method of a class used in Symfony2 project with PHPUnit.
I'm using the private methods testing strategy (through reflection) described by many developers such as http://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-using-phpunit/
But unfortunately, I got the following error:
There was 1 error: 1) My\CalendarBundle\Tests\Calendar\CalendarTest::testCalculateDaysPreviousMonth
ReflectionException: Class Calendar does not exist /Library/WebServer/Documents/calendar/src/My/CalendarBundle/Tests/Calendar/CalendarTest.php:47
<?php
namespace My\CalendarBundle\Tests\Calendar;
use My\CalendarBundle\Calendar\Calendar;
class CalendarTest
{
//this method works fine
public function testGetNextYear()
{
$this->calendar = new Calendar('12', '2012', $this->get('translator'));
$result = $this->calendar->getNextYear();
$this->assertEquals(2013, $result);
}
public function testCalculateDaysPreviousMonth()
{
$reflectionCalendar = new \ReflectionClass('Calendar'); //this is the line
$method = $reflectionCalendar->getMethod('calculateDaysPreviousMonth');
$method->setAccessible(true);
$this->assertEquals(5, $method->invokeArgs($this->calendar, array()));
}
}
Why?
Thank you in advance
You need to use the whole namespaced class name when creating your reflection method, even if you include a use statement.
new \ReflectionClass('My\CalendarBundle\Calendar\Calendar');
This is because you are passing the class name as a string to the constructor, so it doesn't know about your use statement and is looking for the class name in the global namespace.
Also, for what it's worth, you don't actually need to create a ReflectionClass, then call getMethod() on it. Rather, you can directly create a ReflectionMethod object.
new \ReflectionMethod('My\CalendarBundle\Calendar\Calendar', 'calculateDaysPreviousMonth');
That should be essentially the same, but a bit shorter.

Resources