简体   繁体   中英

Calling Java class attributes and methods from Kotlin class

I am trying to access public attributes and public functions in java class, inside a kotlin class. Whenever I try to REPL it using android studio's kotlin REPL, it throws a stub or AndroidManifest error, and when I run it in an emulator, it hangs.

Can someone please provide the right steps to access java class methods and attributes, using a kotlin class?

 // Java class start public class MyJavaClass extends Activity { public String myName = "Hello"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public String getMyString(String name){ myName = name; return myName; } } // Java class end ------------------------------------------------------------------------ // Kotlin class start class ConversationActivity { private val myJavaClass = MyJavaClass() Log.d("TEST", myJavaClass.myName) override fun replyTo(**some random params**){ Log.d("TEST", myJavaClass.getMyString("ok")) } } // Kotlin class end

UPDATE Java methods and attributes are accessible in a kotlin in the same manner mentioned in the above question snippet.

The reason why they were inaccessible and throwing errors was because they were being accessed from a Java Activity class. These attributes and methods are perfectly accessible from a java non-activity class. As activity classes have protected methods of life cycle, they are not accessible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM