-3

I have this method stub:

public <T extends Things> T createInstance(Class<T> clazz) {
    return null;
}

How can I create a Things object without reflection?

Nissa
  • 4,636
  • 8
  • 29
  • 37
Mentha
  • 73
  • 5

1 Answers1

3

You can't. Just by having Class<T> you are already using reflection.

In Java class T can come from a library that is compiled separately (sooner or later) from your code. This means that a runtime representation of the class must be used to create the instance.

As far as I understand, C++ does allow a non-reflective instantiation, but you need to recompile your code using header files for the external library to make it work, and therefore make your code dependent on the library in question.

fdreger
  • 12,264
  • 1
  • 36
  • 42
  • Huh? You can always do: `Class = Whatever.class`. What is "reflection" there? – GhostCat Nov 06 '18 at 14:04
  • @GhostCat Object of java.lang.Class is a runtime representation of a class - which is precisely what introspection is all about. Languages that lack reflection don't have anything like Java `Class`. – fdreger Nov 06 '18 at 14:18
  • Well, I think it is a bit about definitions here. As said: you can easily get to a Class object without "by name" runtime magic. Sure, the things you "do" with the class object most likely resemble "reflection" . – GhostCat Nov 06 '18 at 14:25
  • @GhostCat: reflection is not "by name runtime magic'. It's the fact that there *are* objects in the runtime that represent language constructs. – fdreger Dec 31 '18 at 16:25