我可以使用kotlin.reflect来获取字段的值

时间:2017-09-11 11:56:33

标签: reflection kotlin

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
  <div id="userNotificationForm">
    <form class="new_user_notification" id="new_user_notification" action="/user_notifications" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="nZlQSEjw1o/7DxxOAUmFWJiXr5ZqPodX2tBcCs2qshqLVhM8U/WXuBWocICXDmYOoBnAjhvrEIat972+SkQKEQ==" />

      <div class="field">
        <label for="user_notification_price">Label</label> <span class="required">*</span> <br>
        <input size="30" type="text" name="user_notification[price]" id="user_notification_price" />
      </div>

      <div class="field">
        <label for="user_notification_buy">Condition</label> <span class="required">*</span> <br>
        <select name="user_notification[buy]" id="user_notification_buy"><option value="">Select Notification Time</option>
<option value="false">Above</option>
<option value="true">Below</option></select>
        <p class='error'></p>
      </div>

      <div class="actions buttonContainer">
        <input type="submit" name="commit" value="Submit" id="submit" class="button btn" data-disable-with="Submit" />
      </div>

    </form>
  </div>
</div>

似乎我无法通过 A :: p 获得p, 或者我只能通过java获得它?

我的kotlin版本是

class A{
     private var p:MyObj? = null
}

1 个答案:

答案 0 :(得分:1)

你不能得到它,因为你在属性为private时在该类之外进行。你有几个选择:

  1. 创建一个返回this::pfun func(): KProperty0<MyObj?> = this::p
  2. 的函数
  3. 制作该属性public
  4. 使用反射。 这可能是最慢,性能最差且非常紧密耦合的选项。只有在您不能使用其他人的情况下才能使用它。您可以使用Kotlin的反映:A::class.memberProperties.find { it.name == "p" } as KProperty1<A, MyObj?>