<p>I'm writing a custom controller with Kubebuilder framework, in one method, I got an object of type <a href="https://godoc.org/k8s.io/apimachinery/pkg/runtime#Object" rel="nofollow noreferrer"><code>runtime.Object</code></a>, I know I should be able to convert it to the specific type say <code>MyCustomResource</code>, but I cannot figure out how from the doc.</p>

Dagang
<p>It should be as easy as this:</p>

<pre class="lang-golang prettyprint-override"><code>func convertToMyCustomResource(obj runtime.Object) *v1alpha1.MyCustomResource {
  myobj := obj.(*v1alpha1.MyCustomResource)
  return myobj
}
</code></pre>

<p>If this produces an error (e.g. Impossible type assertion), make sure <code>MyCustomResource</code> satisfies the <a href="https://godoc.org/k8s.io/apimachinery/pkg/runtime#Object" rel="nofollow noreferrer"><code>runtime.Object</code></a> interface; i.e.</p>

<ol>
<li><p>Run the controller-gen tool to generate the <code>DeepCopyObject</code> method</p>

<pre><code>go run vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go paths=./api/... object
</code></pre></li>
<li><p>Add the <code>"k8s.io/apimachinery/pkg/apis/meta/v1".TypeMeta</code> field to the <code>MyCustomResource</code> struct, which implements the <code>GetObjectKind</code> method.</p></li>
</ol>

<pre class="lang-golang prettyprint-override"><code>    import (
      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    )

    type MyCustomResource struct {
      metav1.TypeMeta `json:",inline"`
      // ... other stuff
    }
</code></pre>
