Note that there are some explanatory texts on larger screens.

plurals
  1. POjava force a methods parameter object type based on instance variable
    primarykey
    data
    text
    <p>Can i force a compile error based on a method instance variable? Consider the example classes below. </p> <pre><code>class MyObject{ Class targetClass; public MyObject(Class&lt;? extends Model&gt; targetClass){ this.targetClass = targetClass; } public &lt;T extends Model&gt; void doSomething(T model){ //do some stuff } } class Customer extends Model {} class Document extends Model {} </code></pre> <p>Could i instantiate <code>MyObject</code> with the <code>Customer.class</code> and then have it throw a compile error if i then call the <code>doSomething()</code> method with a <code>Document.class</code> instance? </p> <pre><code>MyObject object = new MyObject(Customer.class); //this shouldn't compile object.doSomething(new Document()); //this would be able to compile object.doSomething(new Customer()); </code></pre> <p>Edit*</p> <p>I'm trying to come up with an ORM Relationship object. I'm instantiating the object with a base <code>Model</code> instance and a target class. For example, i'm creating a <code>HasMany</code> relationship object. I would instantiate the object with a <code>Customer</code> instance and a <code>Document</code> class. In my <code>HashMany</code> object i have a <code>.get()</code> method which returns all <code>Documents</code> attached to the <code>Customer</code> instance. I also have an <code>.attach(Model model)</code> method where i would feed it a <code>Document</code> instance and the method would attach the <code>Document</code> model to the <code>Customer</code> model in the database. I would like to force the <code>.attach(Model model)</code> method to only accept models from the class that the object was instantiated with. In this case, the <code>Document</code> class.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload