I have an object and I need to pass its class to an annotation that takes java.lang.Class, eg:
public @interface PrepareForTest {
Class<?>[] value()
}
object MyObject
@PrepareForTest(Array(?????))
class MySpec ...
I've tried:
@PrepareForTest(Array(classOf[MyObject]))
// error: not found: type MyObject
@PrepareForTest(Array(MyObject))
// error: type mismatch
// found: MyObject.type (with underlying type object MyObject
// required: java.lang.Class[_]
@PrepareForTest(Array(classOf[MyObject.type]))
// error: class type required by MyObject.type found
Not sure what else to try.
To determine the class of a Scala object we use getClass method. This method returns the Class details which is the parent Class of the instance. Below is the example to determine class of a Scala object. In above example, Calling the printClass method with parameter demonstrates the class Scala.
Defining a classClass names should be capitalized. The keyword new is used to create an instance of the class. We call the class like a function, as User() , to create an instance of the class. It is also possible to explicitly use the new keyword, as new User() , although that is usually left out.
In Scala, declarations can be annotated using subtypes of scala. annotation. Annotation . Furthermore, since Scala integrates with Java's annotation system, it's possible to work with annotations produced by a standard Java compiler.
classOf[MyObject$]
does not work because there is no type called MyObject$
.
In fact, the issue did come up before and there is no easy solution. See the discussion on https://lampsvn.epfl.ch/trac/scala/ticket/2453#comment:5
Have a look at the throws
annotation:
@throws(classOf[IOException])
The annotation itself is declared as:
class throws(clazz: Class[_]) extends StaticAnnotation
Doing the same for an object
does not seem to be possible because scala seems to prevent an object from being viewed as having a class in its own right
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With