Kotlin常用注解参数解析

2020-07-07  本文已影响0人  mianbaocheng
class JvmFieldBean{
    var name:String?=null
    @JvmField var age:Int? =null
}

class Test{
    public static void main(String[] args){
        JvmFieldBean bean = new JvmFieldBean();
        bean.setName("aaaa");//访问属性只能通过setter和getter方法
        bean.age = 20;//age可见性为public同时没有生成setter和getter方法
    }
}
 

故对应的java代码为:

class JvmFieldBean{
    private String name;
    public int age;
    
    public void setName(String name){
        this.name = name;
    }

    public String getName(){
      return name;
    }
}
@file:JvmName("JvmNameTest")

package com.today07

var name: String? = null
    @JvmName("setUserName")
    set(value) {
        field = value
    }

@JvmName("getInfos")
fun getInfo() {

}

class Test{
    public static void main(String[] args){
        JvmNameTest.setUserName("aaaa");//设置name属性值只能通过setUserName方法
        JvmNameTest.getName();//获得该属性的值
        JvmNameTest.getInfos();//调用发现没有getInfo的方法
    }
}

故对应的java代码为:

class JvmNameTest{
    private static String name;

    public static void setUserName(String name){
        this.name = name;
    }

    public static String getName(){
        return name;
    }

    public static void getInfos(){}
}
@file:JvmName("Utils")
@file:JvmMultifileClass

package com.today07

 var fieldA: String? = null
fun getA(): String {
    return "this is A"
}

@file:JvmName("Utils")
@file:JvmMultifileClass

package com.today07

fun getB(): String {
    return "this is B"
}

class Test{
    public static void main(String[] args){
        Utils.getFieldA();
        Utils.getA();
        Utils.getB();
    }
}

故对应的java代码为:

class Utils{
    private static String fieldA;
  
    public static String getFieldA(){
        return fieldA
    }

    public static void setFieldA(String fieldA){
        this.fieldA = fieldA;
    }

    public static void getA(){}

    public static void getB(){}
}
  @file:JvmName("JvmOverloadTest")
package com.today07

@JvmOverloads
fun getInfo(name: String, age: Int = 10):String{
    return "name:$name age:$age"
}

class Test{
    public static void main(String[] args){
        JvmOverloadTest.getInfo("aaaa");
        JvmOverloadTest.getInfo("bbbb",20);
    }
}

故对应的java代码为:

class JvmOverloadTest{
      public static String getInfo(String name){
          this(name,10)
      }
      
      public static String getInfo(String name,int age){
            return "name:$name age:$age"
      }
}
package com.today07

object ObjectTest {
    val name:String? =null
    @JvmStatic
    var age:String? =null
    @JvmField
    var sex:Boolean? =null
    fun getTest(){}

    @JvmStatic
    fun getTestB(){

    }
}

class Test{
    public static void main(String[] args){
        ObjectTest.INSTANCE.getTest();
        ObjectTest.getTestB();
        ObjectTest.INSTANCE.getName();
        ObjectTest.getAge();
        ObjectTest.sex = false;
    }
}
上一篇下一篇

猜你喜欢

热点阅读