I am trying to use a Scala class that has a default argument:
object SimpleCredStashClient {
def apply(kms: AWSKMSClient, dynamo: AmazonDynamoDBClient, aes: AESEncryption = DefaultAESEncryption)
...
}
When I try to instantiate an instance of this class from Java, I get the error:
Error:(489, 43) java: cannot find symbol
symbol: method SimpleCredStashClient(com.amazonaws.services.kms.AWSKMSClient,com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient)
location: class com.engineersgate.build.util.CredentialsUtil
DefaultAESEncryption is a Scala object. How do I access the Scala object in Java?
Default arguments become synthetic methods of the form <meth>$default$<idx>(). Further, instances of an object A may be found at A$.MODULE$ (if A is a top-level object), or at outer.A() (if A is defined as something like class O { object A }).Therefore, there are two ways to do this:
Direct usage of object:
SimpleCredStashClient.apply(
kms,
dynamo,
DefaultAESEncryption$.MODULE$
);
Default argument:
SimpleCredStashClient.apply(
kms,
dynamo,
SimpleCredStashClient.apply$default$3()
);
The first one certainly looks better, but if the default argument ever changes, you'll have to update this code too. In the second one, the argument is whatever the default argument is, and will only break if the argument stops having a default, or changes its index. Scala uses the second method when compiled.
Related
I have a Groovy class:
class SomeGroovyThing {
String name
}
And in Java I receive a reference to an instance of this class as an Object:
Object o = project.getExtensions().getByName("groovyThing")
I can't cast the Object because I don't have access to the Groovy class in Java (for unrelated reasons). How can I retrieve the value of the name property (i.e. I want to do o.name but obviously that doesn't work).
I am wanting to do some sort of Reflection, but the fact that my Object is a Groovy class is throwing a wrench in things.
You can do this using Reflection.
You can get it:
String name=(String)o.getClass().getField("name").get(o);
Or set it:
o.getClass().getField("name").set(o,name);
If name is private, you can set or get it using the setter/getter methods(getMethod() in Class) or use setAccessible(true) on the Field.
I am trying to use the hidden package manager method installPackage via reflections.
My major problem is that one of its parameters is another hidden class android.content.pm.IPackageInstallObserver. How can I get the TYPE of that class (not an instance of it)?
val cPackageManager = Class.forName("android.content.pm.PackageManager")
val cPackageInstallObserver = Class.forName("android.content.pm.IPackageInstallObserver")
// here I need the IPackageInstallObserver type as a parameter type to look up the method
val installPackageMethod = cPackageManager.getMethod("installPackage", Uri::class.java, cPackageInstallObserver::class.java, Integer.TYPE, String::class.java)
In the way above, cPackageInstallObserver::class.java resolves to only a Class but not the actual type I need.
Does anybody have a solution for that?
You just did a simple mistake here
Uri::class.java, cPackageInstallObserver, Integer.TYPE, String::class.java)
As cPackageInstallObserver is already a class you need, as Class.forName returns a Class type, but you used cPackageInstallObserver::class.java so it is just same as doing String.class.getClass() in java, so just Class.class.
Java 8 has the ability to acquire method parameter names using Reflection API.
How can I get these method parameter names?
As per my knowledge, class files do not store formal parameter names. How can I get these using reflection?
How can i get these method parameter names?
Basically, you need to:
get a reference to a Class
From the Class, get a reference to a Method by calling getDeclaredMethod() or getDeclaredMethods() which returns references to Method objects
From the Method object, call (new as of Java 8) getParameters() which returns an array of Parameter objects
On the Parameter object, call getName()
Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
System.err.println(m.getName());
for (Parameter p : m.getParameters()) {
System.err.println(" " + p.getName());
}
}
Output:
...
indexOf
arg0
indexOf
arg0
arg1
...
Also as per my knowledge .class files do not store formal parameter. Then how can i get them using reflection?
See the javadoc for Parameter.getName():
... If the parameter's name is present, then this method returns the name provided by the class file. Otherwise, this method synthesizes a name of the form argN, where N is the index of the parameter in the descriptor of the method which declares the parameter.
Whether a JDK supports this, is implementation specific (as you can see form the above output, build 125 of JDK 8 does not support it). The class file format supports optional attributes which can be used by a specific JVM/javac implementation and which are ignored by other implementations which do not support it.
Note that you could even generate the above output with arg0, arg1, ... with pre Java 8 JVMs - all you need to know is the parameter count which is accessible through Method.getParameterTypes():
Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
System.err.println(m.getName());
int paramCount = m.getParameterTypes().length;
for (int i = 0; i < paramCount; i++) {
System.err.println(" arg" + i);
}
}
What is new with JDK 8 is that there is an extended API and the possibility for JVMs to provide the real parameter names instead of arg0, arg1, ...
Supporting such optional features is possible through optional attributes which can be attached to the various class file structures. See 4.6. Methods for the method_info structure within a class file. See also 4.7.1. Defining and Naming New Attributes in the JVM spec.
Since with JDK 8, the class file version will be incremented to 52, it would also be possible to change the file format itself to support this feature.
See also JEP 118: Access to Parameter Names at Runtime for more information and implementation alternatives. The proposed implementation model is to add an optional attribute which stores the parameter names. Since the class file format already supports these optional attributes, this would even be possible in a way so that the class files can still be used by older JVMs, where they are simply ignored as demanded by the spec:
Java Virtual Machine implementations are required to silently ignore attributes they do not recognize.
Update
As suggested by #assylias, the source needs to be compiled with the javac command line option -parameters in order to add the meta data for parameter name reflection to the class file. However, this will of course only affect code compiled with this option - the code above will still print arg0, arg1 etc. since the runtime libraries are not be compiled with this flag and hence do not contain the necessary entries in the class files.
Thanks Andreas, but finally i got the complete solution from oracle Tutorials on Method Parameters
It says,
You can obtain the names of the formal parameters of any method or
constructor with the method
java.lang.reflect.Executable.getParameters. (The classes Method and
Constructor extend the class Executable and therefore inherit the
method Executable.getParameters.) However, .class files do not store
formal parameter names by default. This is because many tools that
produce and consume class files may not expect the larger static and
dynamic footprint of .class files that contain parameter names. In
particular, these tools would have to handle larger .class files, and
the Java Virtual Machine (JVM) would use more memory. In addition,
some parameter names, such as secret or password, may expose
information about security-sensitive methods.
To store formal parameter names in a particular .class file, and thus
enable the Reflection API to retrieve formal parameter names, compile
the source file with the -parameters option to the javac compiler.
How to Compile
Remember to compile the with the -parameters compiler option
Expected Output(For complete example visit the link mentioned above)
java MethodParameterSpy ExampleMethods
This command prints the following:
Number of constructors: 1
Constructor #1
public ExampleMethods()
Number of declared constructors: 1
Declared constructor #1
public ExampleMethods()
Number of methods: 4
Method #1
public boolean ExampleMethods.simpleMethod(java.lang.String,int)
Return type: boolean
Generic return type: boolean
Parameter class: class java.lang.String
Parameter name: stringParam
Modifiers: 0
Is implicit?: false
Is name present?: true
Is synthetic?: false
Parameter class: int
Parameter name: intParam
Modifiers: 0
Is implicit?: false
Is name present?: true
Is synthetic?: false
Method #2
public int ExampleMethods.varArgsMethod(java.lang.String...)
Return type: int
Generic return type: int
Parameter class: class [Ljava.lang.String;
Parameter name: manyStrings
Modifiers: 0
Is implicit?: false
Is name present?: true
Is synthetic?: false
Method #3
public boolean ExampleMethods.methodWithList(java.util.List<java.lang.String>)
Return type: boolean
Generic return type: boolean
Parameter class: interface java.util.List
Parameter name: listParam
Modifiers: 0
Is implicit?: false
Is name present?: true
Is synthetic?: false
Method #4
public <T> void ExampleMethods.genericMethod(T[],java.util.Collection<T>)
Return type: void
Generic return type: void
Parameter class: class [Ljava.lang.Object;
Parameter name: a
Modifiers: 0
Is implicit?: false
Is name present?: true
Is synthetic?: false
Parameter class: interface java.util.Collection
Parameter name: c
Modifiers: 0
Is implicit?: false
Is name present?: true
Is synthetic?: false
as per Store information about method parameters (usable via reflection) in intellij 13, the equivalent of "javac -parameters" within the Eclipse IDE is 'Store information about method parameters (usable via reflection)' in Window -> Preferences -> Java -> Compiler.
You can use Paranamer lib (https://github.com/paul-hammant/paranamer)
Sample code that works for me:
import com.thoughtworks.paranamer.AnnotationParanamer;
import com.thoughtworks.paranamer.BytecodeReadingParanamer;
import com.thoughtworks.paranamer.CachingParanamer;
import com.thoughtworks.paranamer.Paranamer;
Paranamer info = new CachingParanamer(new AnnotationParanamer(new BytecodeReadingParanamer()));
Method method = Foo.class.getMethod(...);
String[] parameterNames = info.lookupParameterNames(method);
If you use Maven then put this dependency in your pom.xml:
<dependency>
<groupId>com.thoughtworks.paranamer</groupId>
<artifactId>paranamer</artifactId>
<version>2.8</version>
</dependency>
I have some legacy Java code that defines a generic payload variable somewhere outside of my control (i.e. I can not change its type):
// Java code
Wrapper<? extends SomeBaseType> payload = ...
I receive such a payload value as a method parameter in my code and want to pass it on to a Scala case class (to use as message with an actor system), but do not get the definitions right such that I do not get at least a compiler warning.
// still Java code
ScalaMessage msg = new ScalaMessage(payload);
This gives a compiler warning "Type safety: contructor... belongs to raw type..."
The Scala case class is defined as:
// Scala code
case class ScalaMessage[T <: SomeBaseType](payload: Wrapper[T])
How can I define the case class such that the code compiles cleanly? (sadly, changing the code of the Java Wrapper class or the type of the payload parameter is not an option)
Updated to clarify the origin of the payload parameter
Added For comparison, in Java I can define a parameter just in the same way as the payload variable is defined:
// Java code
void doSomethingWith(Wrapper<? extends SomeBaseType> payload) {}
and call it accordingly
// Java code
doSomethingWith(payload)
But I can't instantiate e.g. a Wrapper object directly without getting a "raw type" warning. Here, I need to use a static helper method:
static <T> Wrapper<T> of(T value) {
return new Wrapper<T>(value);
}
and use this static helper to instantiate a Wrapper object:
// Java code
MyDerivedType value = ... // constructed elsewhere, actual type is not known!
Wrapper<? extends SomeBaseType> payload = Wrapper.of(value);
Solution
I can add a similar helper method to a Scala companion object:
// Scala code
object ScalaMessageHelper {
def apply[T <: SomeBaseType](payload: Wrapper[T]) =
new ScalaMessage(payload)
}
object ScalaMessageHelper2 {
def apply[T <: SomeBaseType](payload: Wrapper[T]) =
ScalaMessage(payload) // uses implicit apply() method of case class
}
and use this from Java to instantiate the ScalaMessage class w/o problems:
// Java code
ScalaMessage msg = ScalaMessageHelper.apply(payload);
Unless someone comes up with a more elegant solution, I will extract this as an answer...
Thank you!
I think the problem is that in Java if you do the following:
ScalaMessage msg = new ScalaMessage(payload);
Then you are instantiating ScalaMessage using its raw type. Or in other words, you use ScalaMessage as a non generic type (when Java introduced generics, they kept the ability to treat a generic class as a non-generic one, mostly for backward compatibility).
You should simply specify the type parameters when instantiating ScalaMessage:
// (here T = MyDerivedType, where MyDerivedType must extend SomeBaseType
ScalaMessage<MyDerivedType> msg = new ScalaMessage<>(payload);
UPDATE: After seeing your comment, I actually tried it in a dummy project, and I actually get an error:
[error] C:\Code\sandbox\src\main\java\bla\Test.java:8: cannot find symbol
[error] symbol : constructor ScalaMessage(bla.Wrapper<capture#64 of ? extends bla.SomeBaseType>)
[error] location: class test.ScalaMessage<bla.SomeBaseType>
[error] ScalaMessage<SomeBaseType> msg = new ScalaMessage<SomeBaseType>(payload);
It seems like a mismatch between java generics (that we can emulate through exitsentials in scala ) and scala generics. You can fix this by just dropping the type parameter in ScalaMessage and using existentials instead:
case class ScalaMessage(payload: Wrapper[_ <: SomeBaseType])
and then instantiate it in java like this:
new ScalaMessage(payload)
This works. However, now ScalaMessage is not generic anymore, which might be a problem if you want use it with more refined paylods (say a Wrapper<? extends MyDerivedType>).
To fix this, let's do yet another small change to ScalaMessage:
case class ScalaMessage[T<:SomeBaseType](payload: Wrapper[_ <: T])
And then in java:
ScalaMessage<SomeBaseType> msg = new ScalaMessage<SomeBaseType>(payload);
Problem solved :)
What you are experiencing is the fact that Java Generics are poorly implemented. You can't correctly implement covariance and contravariance in Java and you have to use wildcards.
case class ScalaMessage[T <: SomeBaseType](payload: Wrapper[T])
If you provide a Wrapper[T], this will work correctly and you'll create an instance of a ScalaMessage[T]
What you would like to do is to be able to create a ScalaMessage[T] from a Wrapper[K] where K<:T is unknown. However, this is possible only if
Wrapper[K]<:Wrapper[T] for K<:T
This is exactly the definition of variance. Since generics in Java are invariant, the operation is illegal. The only solution that you have is to change the signature of the constructor
class ScalaMessage[T](wrapper:Wrapper[_<:T])
If however the Wrapper was implemented correctly in Scala using type variance
class Wrapper[+T]
class ScalaMessage[+T](wrapper:Wrapper[T])
object ScalaMessage {
class A
class B extends A
val myVal:Wrapper[_<:A] = new Wrapper[B]()
val message:ScalaMessage[A] = new ScalaMessage[A](myVal)
}
Everything will compile smoothly and elegantly :)
I got a strange problem with a call to a Java method from JRuby.
In my Java class these methods are defined twice, and it appears JRuby calls the wrong one.
So I tried to use java_method, but I always got a:
TypeError: cannot convert instance of class org.jruby.RubyModule to class java.lang.Class
Here's my Java code:
public class Renderer {
...
public void addRenderer(IElementRenderer r) {
System.out.println("Added element render: " + r.getClass().toString());
basicRenderers.add(r);
rendererMap.put(r.elementClass(), r);
}
public void addRenderer(IBasicRenderer r) {
System.out.println("SHOULD NOT GO THERE !!");
basicRenderers.add(r);
}
}
and my JRuby code:
add_renderer = renderer.java_method :add_renderer, [Java::dragon.render.IElementRenderer]
add_renderer.call TextRenderer.new
I also tried with java_send but I got the same error:
renderer.java_send(:add_renderer, [Java::dragon.render.IElementRenderer], TextRenderer.new)
Next, I tried with:
renderer.add_renderer(TextRenderer.new.to_java(IElementRenderer))
This time no errors but the wrong method is called ...
How can I fix this problem?
You can fix that cannot convert instance of class org.jruby.RubyModule to class java.lang.Class using java.lang.Class.for_name
In your case, it is
add_renderer = renderer.java_method :add_renderer, [java.lang.Class.for_name("dragon.render.IElementRenderer")]
This is because java interfaces become Ruby Modules by default and the second argument to :java_method expects an array of Class objects.
You can print the matched method to see it is matching the intended method.
For example, I see below code is matching the println(String) on System.out.
>>java.lang.System.out.java_method "println", [java.lang.Class.for_name("java.lang.String")]
#<Method: Java::JavaIo::PrintStream#(java.lang.String)>
I've had problems like this before. It was many versions ago and I think JRuby's method matching algorithm has improvedd over time. Are you using the latest JRuby?
If nothing else works, you may need to add another method, or a wrapper class. Something that distinguishes your methods by name or number of parameters, not just parameter type.