Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an java.lang.Class of a scala object for an annotation argument

Tags:

scala

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.

like image 428
memelet Avatar asked Feb 19 '10 07:02

memelet


People also ask

How do you find the class of an object in Scala?

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.

How to define a class in 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.

Does Scala have annotations?

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.


2 Answers

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

like image 124
Lukas Rytz Avatar answered Oct 08 '22 19:10

Lukas Rytz


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

like image 24
oxbow_lakes Avatar answered Oct 08 '22 20:10

oxbow_lakes