I am experiencing an issue regarding access of an abstract class.
For background, I have an abstract class in a common module. The abstract class is just setters/getters for some values.
abstract class BaseConfiguration {
abstract var key: String?
abstract var token: String?
}
The common module is used by another module that is a SDK. So, in gradle this common module is implemented.
Gradle
implementation project(":common")
Inside of the SDK module, there are public interfaces to allow the setting/getting of the values in the BaseConfiguration file.
The conflict I am running into is that for Kotlin everything works fine. I am able to create a project, then add the SDK as a dependency and then set values for the BaseConfiguration through the provided interfaces in the SDK.
However, when I try to use the Java language, I am receiving a "cannot access BaseConfiguration" error. The only thing that seems to resolve this issue is to update my SDK gradle to api.
Gradle Changes
api project(":common")
I have concerns with this change, because the common module is supposed to be internal and only used by the SDK. The app level should not have access to it. The app should only access the provided interfaces by the SDK.
Does anyone know why this is working perfectly with Kotlin, but not with Java? What am I doing wrong?
Further Notes:
When decompiling the Kotlin to Java for the BaseConfiguration class it shows that everything is public.
public abstract class BaseConfiguration {
#Nullable
public abstract String getKey();
public abstract void setKey(#Nullable String var1);
#Nullable
public abstract String getToken();
public abstract void setToken(#Nullable String var1);
}
By default, java's class visibility is package private. That means any file in the same package can access your abstract BaseConfiguration.
In kotlin, the default is public.
I suppose it is this visibility that is causing the issue. You should not use api for common module if the app module is not using it. Common's visibility should only be exposed to the SDK module as its direct neighbour. You are right to not expose the common module as a transitive dependency of app module.
Trying being explicit about the class dependency:
public abstract class BaseConfiguration {
abstract var key: String?
abstract var token: String?
}
I would take a look at the compiled java class by the kotlin compiler and see how it generates it.
Related
I need to support two versions of a dependency, which have the same API but different package names.
How do I handle this without maintaining two versions of my code, with the only change being the import statement?
For local variables, I guess I could use reflection (ugly!), but I use the classes in question as method argument. If I don't want to pass around Object instances, what else can I do to abstract from the package name?
Is it maybe possible to apply a self-made interface - which is compatible to the API - to existing instances and pass them around as instance of this interface?
I am mostly actually using xtend for my code, if that changes the answer.
Since you're using Xtend, here's a solution that makes use of Xtend's #Delegate annotation. There might be better solutions that aren't based on Xtend though and this will only work for simple APIs that only consist of interfaces with exactly the same method signatures.
So assuming you have interfaces with exactly the same method signatures in different packages, e.g. like this:
package vendor.api1
interface Greeter {
def void sayHello(String name)
}
package vendor.api2
interface Greeter {
def void sayHello(String name)
}
Then you can combine both into a single interface and only use only this combined interface in your code.
package example.api
interface Greeter extends vendor.api1.Greeter, vendor.api2.Greeter {
}
This is also possible in Java so far but you would have to write a lot boilerplate for each interface method to make it work. In Xtend you can use #Delegate instead to automatically generate everything without having to care how many methods the interface has or what they look like:
package example.internal
import example.api.Greeter
import org.eclipse.xtend.lib.annotations.Delegate
import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
#FinalFieldsConstructor
class GreeterImpl implements Greeter {
#Delegate val Api delegate
}
#FinalFieldsConstructor
class Greeter1Wrapper implements Greeter {
#Delegate val vendor.api1.Greeter delegate
}
#FinalFieldsConstructor
class Greeter2Wrapper implements Greeter {
#Delegate val vendor.api2.Greeter delegate
}
Both Greeter1Wrapper and Greeter2Wrapper actually implement the interface of both packages here but since the signature is identical all methods are forwarded to the respective delegate instance. These wrappers are necessary because the delegate of GreeterImpl needs to implement the same interface as GreeterImpl (usually a single delegate would be enough if the packages were the same).
Now you can decide at run-time which version to use.
val vendor.api1.Greeter greeterApi1 = ... // get from vendor API
val vendor.api2.Greeter greeterApi2 = ... // get from vendor API
val apiWrapper = switch version {
case 1: new Greeter1Wrapper(greeterApi1)
case 2: new Greeter2Wrapper(greeterApi2)
}
val example.api.Greeter myGreeter = new GreeterImpl(apiWrapper)
myGreeter.sayHello("world")
This pattern can be repeated for all interfaces. You might be able to avoid even more boilerplate by implementing a custom active annotation processor that generates all of the required classes from a single annotation.
I am new to Kotlin and trying out to write some project using the language.
I am using Java library and extending a class from the library in my project and I am seeing this error message.
'public' function exposes its 'public/*package*/' return type argument FooSettings
I understand the problem is but I am not sure how to fix it in Kotlin since I am still trying get familiar with Kotlin.
I can see that Kotlin is being smart and only trying to return of type that extends FooSettings. However the problem is FooSettings is package public only which means that I cannot access if in my Kotlin project.
I did some research about Kotlin generics and use of in or out but I wasn't able to fix the problem.
Is there any work around that I can do in my Kotlin project to fix the error I am seeing?
Code snippet
This is sample of Java library class:
Note, I have no way to changing the implementation of the library. I must use this Library and extend it in Kotlin.
It seems odd to me that the java library is written such a way and expect it to be overridden but that is question for another day.
import java.util.Collections;
import java.util.List;
public abstract class ClassA {
public List<FooBuilder<?>> getBuilder(Foo foo) {
return Collections.emptyList();
}
}
public class Foo {
}
public abstract class FooBuilder<U extends FooBuilder.FooSettings> {
// implementation of Class
abstract static class FooSettings {
// implementation of Class
}
}
Normally Java classes would override the method like such:
import java.util.List;
public class MyJavaClassA extends ClassA {
#Override public List<FooBuilder<?>> getBuilder(final Foo foo) {
// implementation
}
}
But I am trying to write in Kotlin such that it looks like: Reminder that this Kotlin is depending on the Java library and does not have access to package public classes.
class MyKotlinClassA : ClassA() {
override fun getBuilder(foo: Foo): MutableList<FooBuilder<*>> {
// implementation
}
}
This causes error
'public' function exposes its 'public/*package*/' return type argument FooSettings
I presume that by "package public" you meant "package private"? In your example, FooBuilder.FooSettings has no visibility modifier so uses the Java default of package private. Assuming that's what you meant...
You will be able to access the package private class, FooSettings, in your Kotlin code, but only if you put that Kotlin code in a package matching the one where FooSettings is declared.
You'll still get the same compilation error, but that's not because you can't access the type: it's because you're trying to use it in a context which is more visible than the type's declaration. i.e. you're trying to take a package private type and use it as part of a public method's signature, which isn't allowed. To get round that problem you need to mark your Kotlin class as internal.
It's might also be worth mentioning that internal for Kotlin means it's visible in that module, not in that package. This is all explained in more detail here.
In my case, I was getting this error because I was importing a kotlin class variable from another java file which raised because of the auto conversion from java to kotlin by Android Studio.
I was able to fix it by changing all the references of the variable in the java file to its setters and getters.
eg:
// kotlin file
internal open class BubbleBaseLayout : FrameLayout {
var windowManager: WindowManager? = null
lateinit var viewParams: WindowManager.LayoutParams
// defined here
var layoutCoordinator: BubblesLayoutCoordinator? = null
// ...
}
// Java file
// This variable
if (layoutCoordinator != null) { ... }
Needs to be changed to
// layoutCoordinator to getlayoutCoordinator everywhere
if(getlayoutCoordinator() != null){ ... }
I am building my Spring Boot 1.5 + Kotlin 1.2.41 project into a jar. One of the interfaces in the jar has the #JvmDefault and it compiles fine with the flag (if I remove the flag, it fails).
Now, I am trying to use this interface in another java project, in which I define the Kotlin project as a dependency.
In one implementing class, I don't override the default method. Intellij seems to be OK with it, as it doesn't complain. However, when I compile with Maven, I get :
[ERROR] attempting to assign weaker access privileges; was public
If I implement the method (with some dummy implementation), then it compiles... but it defeats the purpose of the default interface.
Any idea what could be wrong ?
When opening the Kotlin interface code from the java project, here's the decompiled code I see :
public interface CrawlerOutput {
#kotlin.jvm.JvmDefault public open fun finalize(): kotlin.Unit { /* compiled code */ }
public abstract fun output(analyzedRepository: com.myCompany.Repository): kotlin.Unit
}
My java code implementing the interface :
public class CsvOutput implements CrawlerOutput {
#Override
public void output(Repository repository) throws IOException {
log.info("own output is receiving some data !");
}
/**
* IF I REMOVE BELOW METHOD, MAVEN CAN'T COMPILE IT ANYMORE,
* COMPLAINING OF WEAKER ACCESS PRIVILEGE
*/
#Override
public void finalize(){
}
}
Am I missing something ?
Thanks
Vincent
Your method name conflicts with java.lang.Object.finalize(). The error should be fixed if you choose a different method name.
Android Studio and JVM always update its versions. As a result of that some of you may experience this error message.
Inheritance from an interface with '#JvmDefault' members is only allowed with -Xjvm-default option
Don't worry . The solution is very simple. Just add below code part to the end of android block of your app level build.gradle file and sync.
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
freeCompilerArgs += [
"-Xjvm-default=all",
]
}
}
I have written an annotation processor that generates a builder class for my classes annotated with #DataBuilder
#Target(AnnotationTarget.CLASS)
#Retention(AnnotationRetention.SOURCE)
annotation class DataBuilder
My classes annotated with this annotation are located in the com.my.package.model package and the generated builder class is also located in the same package com.my.package.model but in the generated directory of course build/generated/source/kapt/debug/com/my/package/model/MyModelBuilder.kt, I can use these generated classes fine inside of my model classes(written in Kotlin)
BUT I can NOT use the generated MyModelBuilder Kotlin class inside of a java class as a class member
package com.my.package.home;
import com.my.package.model.MyModelBuilder;
public class Home {
MyModelBuilder builder; // <=== AS recognizes the class, but I'm having an compilation issue
}
Android Studio recognizes the class, but I’m having this compilation issue
com/my/package/home/Home.java:4: error: cannot find symbol
MyModelBuilder builder;
^
symbol: class MyModelBuilder
location: class Home
it’s weird because I can use this generated builder class only inside of methods, this code compiles fine:
package com.my.package.home;
import com.my.package.model.MyModelBuilder;
public class Home {
public void hello() {
MyModelBuilder builder;
}
}
could somebody here help me to understand this behavior and how to fix this? In advance, thanks!
UPDATE
I just created this repo with the necessary code to replicate the issue
https://github.com/epool/HelloKapt
The project works fine after cloning and running, to replicate the issue please un-comment this line https://github.com/epool/HelloKapt/blob/master/app/src/main/java/com/nearsoft/hellokapt/app/MainActivity.java#L13
Note: If I convert my MainActivity.java class to Kotlin(MainActivity.kt) the issues is NOT reproducible and works fine, but I don’t want to do so due to some project limitations so far
Kotlin Issue: https://youtrack.jetbrains.net/issue/KT-24591
Looking at your Github project, I notice that you don't declare a dependency on kotlin-stdlib-jdk7 in the app module. When I build the module, compiler emits the following warnings:
warning: unknown enum constant AnnotationTarget.CLASS
reason: class file for kotlin.annotation.AnnotationTarget not found
warning: unknown enum constant AnnotationRetention.SOURCE
reason: class file for kotlin.annotation.AnnotationRetention not found
warning: unknown enum constant AnnotationTarget.CLASS
reason: class file for kotlin.annotation.AnnotationTarget not found
Since kotlin-stdlib-jdk7 is declared as implementation in the annotations module, the app module doesn't see it as a transitive dependency, that might be the reason why compilation fails. To fix it, you should probably declare the correct dependency in the app module, or at least use apiElements scope for kotlin-stdlib-jdk7 in annotations.
The fact that the IDE doesn't notify you that compilation failed might be a tools bug, but there's definitely no underlying Kotlin compiler issue.
I'm having troubles trying to get my external Java project so I can use Android classes on it as well. The library is already integrated on the Android project. For instance: I have several model classes on it that I would want to implement Parcelable so they can be seriallized accordingly, but none of the Android classes are available on them.
Clarification I only did this in order to try to solve the issue
So far I've only tried:
Changing and matching the external library's package:
Package name in Android
com.domain.androidproject
Library's package originally
com.domain.libproject
Changed to:
com.dommain.androidproject.libproject
But no luck so far. I imported the library as a Gradle external project vía:
compile project(path: ':LibProject')
Thank you for your help.
You'll have to define a binding between your pure java library and android. You could use Dependency injection to inject the models using the class signature, and then define the parcelable models inside the app (or into another project, like a plugin). Or you could achieve the same using generics. keep in mind, since the java library is already compiled, technically, you can't change it by importing it into the android project (I've seen people "rewriting" some files from a dependency and then adding them with the whole original path to fool the classpath, but that's highly risky since you are not gonna be able to interact with the rest of the dependency's code and if something changes, the thing will break).
if you have access to the pure java's library sourcecode, then modify it to use factories or providers of models. If not, extend the models, add parcelable support, and attempt to use those instead of the original model classes.
Example:
let's suppose we have a model and some functions using it:
public class myModel{
private int id;
private String name;
public void setId(int id){
this.id = id;
}
//more getters and setters
}
public interface myModelCreator<T>{
public myModel create(T toModel);
public T uncreate(myModel fromModel);
}
public static void doSomething(myModel model){
//some library operations
}
Now, in the android project:
public class myAndroidModel extends myModel implements Parcelable{
/*Implements the parcelable methods using the class accessors, or you can change the myModel members to protected.*/
}
public class myAndroidModelCreator implements myModelCreator<myAndroidModel>{
#Override
public myModel create(myAndroidModel toModel){
//create the myModel using the parcelable class.
}
#Override
public myAndroidModel uncreate(myModel fromModel){
//reverse operation.
}
}
Now, in the android project, you can use the parcelable subclass everywhere, and everytime you need to call the library, you can supply the creator interface using the parcelables as arguments.
Another alternative would be changing the library method signatures to something like this:
public static void<T extends myModel> doSomething(T model){
//some library operations
}
So you can directly consume the parcelable subclasses. But depending on your hierarchy, that may be not possible. Lastly, you could attempt to implement dependency injection into the java project using Guice and Roboguice in the android project. Since roboguice uses guice, it is possible they can interoperate, but that's a long shot.
I like Fco P.'s answer, but for the sake of completness, here is an alternative answer.
Use json to serialize objects, rather than Parcelable. You can then put your serialized json as a string extra in intent or as string in bundles.
it's faster to implement than using Parcelable, with libraries such as Google GSON or Square moshi.
it's less performant than Parcelable
Generally if you want to make use of classes in another project/library:
File -> New -> Import Module -> Navigate to the directory of an old project/Library -> Ok
Check off the modules you want to import -> OK
Right click the app module -> Open Module Settings -> dependencies -> + -> Module -> The new Module.
Your project should then be usable in whatever project you just did that for.
Create an android library project with packagename com.domain.libproject
Copy all the sources in src folder.
Update jar dependencies in build.gradle and after that you can make your class in the library parcelable.
Let me know if any issues.
Best regds