0

So I'm trying to create an instance of a class using following statements (simplified):

class A
classOf[A].newInstance()

The call throws:

java.lang.InstantiationException: A$A426$A$A426$A
Caused by: java.lang.NoSuchMethodException: A$A426$A$A426$A.<init>()

I did try defining init() method with different variations with no success. What am I missing?

Thanks in advance.


Related, didn't work for me:

No such method exception Hadoop <init>

This answer

Community
  • 1
  • 1
vim
  • 454
  • 4
  • 11
  • Class A has a constructor without arguments? – pasaba por aqui Feb 17 '16 at 09:22
  • @pasabaporaqui I can't say for internal implementation but statement `new A` is valid – vim Feb 17 '16 at 09:24
  • Where are you declaring A? – Clive Evans Feb 17 '16 at 12:25
  • 1
    Typing in those two exact lines works in the Scala REPL (v2.11.7). Show us your *real* code that has this problem, instead of this simplified example. The error means that the class has no no-args constructor. An `init()` method is not a constructor, so adding an `init()` method will not help. – Jesper Feb 17 '16 at 12:44

2 Answers2

1

I suspect your problem is that A is being declared inside anther class. See this example:

import org.specs2.mutable.Specification

class StackoverflowSpec extends Specification {

  class B

  "A" should {
    "be instantiatable" in {
      classOf[A].newInstance() must not(beNull)
    }
  }

  "B" should {
    "throw an instantiation exception" in {
      classOf[B].newInstance must throwAn[InstantiationException]
    }
  }
}

class A

I think that what's happening is that in the jvm, your classes are A and StackoverflowSpec$B, and that StackoverflowSpec$B requires a StackoverflowSpec to be passed in to it's constructor, because it's an inner class.

Clive Evans
  • 658
  • 8
  • 12
0

Thanks for suggestion about inner class but actually it has to do with IntelliJ IDEA 'scala worksheet' -- scala sandbox file with interactive evaluation. For some reason, instantiation described above throws only in a worksheet, it does work in a regular Scala REPL.

vim
  • 454
  • 4
  • 11
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/11301699) – Seyeong Jeong Feb 19 '16 at 00:53
  • I am the author. The actual answer "why it doesn't work" is unknown, because it's IDE defect/feature. – vim Feb 19 '16 at 08:18