1

I want to remove the following import:

import my.package.version.class1

the reason is that I want to pass the version as a parameter so I can have the following options:

my.package.version1.class1
my.package.version2.class1
my.package.version3.class1

When I do it hard-coded like that it works

classOf[my.package.version1.class1].getPackage

But I need it to be a String type so I can append the version each time.

val hh = "my.package."+versionParamater+".class1"



 classOf[hh].getPackage //THIS WONT WORK error: identifier expected but string literal found.

I also tried doing this and it didnt work as well:

 val pkg = Package.getPackage(" my.package.version1.class1");

can you please assist?

2 Answers 2

3

You will have to revert to the java.lang.Class.forName method to get hold of the class. But note that you will get back a Class<?> rather than a Class<class1>. For example:

scala> Class.forName("java.lang.String")
res0: Class[_] = class java.lang.String

You can cast it, though:

scala> res0.asInstanceOf[Class[String]]
res1: Class[String] = class java.lang.String

A mis-cast will not result in a ClassCastException:

scala> res0.asInstanceOf[Class[Integer]]
res2: Class[Integer] = class java.lang.String
Sign up to request clarification or add additional context in comments.

Comments

1

You can use java.lang.Class.forName(fullClassPackage).

Example,

  val versionParamater = "version1"
  val fullPackage = "my.package."+versionParamater+".class1"
  val versionedClass = Class.forName(fullPackage)
  assert(versionedClass.getSimpleName == "class1")
  assert(versionedClass.getPackage.getName == "my.package.version1")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.