Jump to content

how to detect if a class implements an interface


memcallen

Recommended Posts

I've made a battery class which implements a custom interface "IPowerProvider" and a cable which also implements the same interface, when I want to add more cables how could I detect if the class implements my interface?

 

sidenote-I've tried to use instanceof with an instance rather than the class but it didn't work

The proud(ish) developer of Ancients

Link to comment
Share on other sites

something to the effect of invalidCast

 

edit: I probably should have waited till I got in front of my computer, sorry for being short with those responses. Anyway I know this method would work, but back in the day I was taught to avoid catch statements whenever possible, as they were taxing on performance. I'm not sure if that's still the case, or if Java has a specific implementation for the kind of check you are looking for. Maybe someone who drinks more Java can chime in on the %100 official of if this is the best practice, but again, I know it would work. Also, I'm still used to C# at the end of the day where you don't necessarily have to provide the explicit exception type. I was trying to suggest doing it without the try/catch and trying to cast something you know is not IPowerProvider and letting it crash and tell you the exception type; but again, it should be "InvalidCastException", so the code might look like this:

 


try {
   IPowerProvider p = (IPowerProvider) var;
    // success, is IPowerProvider
}
catch(InvalidCastException){
    // not IPowerProvider
}

I'll need help, and I'll give help. Just ask, you know I will!

Link to comment
Share on other sites

I've made a battery class which implements a custom interface "IPowerProvider" and a cable which also implements the same interface, when I want to add more cables how could I detect if the class implements my interface?

 

sidenote-I've tried to use instanceof with an instance rather than the class but it didn't work

 

instanceof is the proper way to do it.  What do you mean it didn't work?

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

Assuming you have an instance of your class (or any instance of any class, really), such as 'Battery battery = new Battery()', then to check if it implements an interface and then use those interface methods, you use the following, which is what everyone else has been trying to say:

// checking if the object implements the interface
if (battery instanceof IPowerProvider) {
// now casting the object to the interface class so you can use the interface methods
IPowerProvider power = (IPowerProvider) battery;
power.someInterfaceMethod();

// which you can also write as one line (after checking instanceof) if you only need to call one method:
((IPowerProvider) battery).someInterfaceMethod();
}

Link to comment
Share on other sites

Assuming you have an instance of your class (or any instance of any class, really), such as 'Battery battery = new Battery()', then to check if it implements an interface and then use those interface methods, you use the following, which is what everyone else has been trying to say:

// checking if the object implements the interface
if (battery instanceof IPowerProvider) {
// now casting the object to the interface class so you can use the interface methods
IPowerProvider power = (IPowerProvider) battery;
power.someInterfaceMethod();

// which you can also write as one line (after checking instanceof) if you only need to call one method:
((IPowerProvider) battery).someInterfaceMethod();
}

 

Definitely this! I'd like to note that I was attempting to offer an alternate solution, assuming instanceof "doesn't work" - but as they pointed out, it should.  ;)

I'll need help, and I'll give help. Just ask, you know I will!

Link to comment
Share on other sites

what I was doing was

 

TileEntity te = world.getTileEntity(x,y-1,z);
if(te!=null)
if(te instanceof IPowerContainer)
System.out.println("yes");

and it wasn't printing anything even though I had a block that properly implemented it and had a tileEntity below my battery

The proud(ish) developer of Ancients

Link to comment
Share on other sites

Well even though you might be confident that the tile entity below the position is there, in computer debugging usually you'll find that something you're sure of isn't actually true.

 

So if I were you I'd add more console output to confirm.  I would output the x, y, z coordinates and I would output the name of the block found at the position.  I would also put in the else clauses for each if statement and put a console printout there too.  for example, you test whether the te is null but it is not clear if that is true or not because you don't get any output. 

 

so if you have console statement showing all the information (position, whether te is null), then you'll be able to debug.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

yeah I have setup my TileEntity correctly it can already store power and save to nbt and all the normal tileEntity stuff also I'm pretty sure that the tileEntity isn't null because I replace the blocks every time I test it

 

In programming, if something isn't working the way you expect then one of your assumptions is wrong.  You have to check everything explicitly.  You think you have a tile entity there, but obviously it isn't being detected.  So you need to prove that the position you're checking is correct, that the tile entity is actually not null, and so forth.

 

This is debugging.  You don't fix it by asking "what's wrong with my code", you fix it by *tracing* your code exactly.  At some point your code is going wrong, so you need to go step by step and prove where it goes wrong.  You have to prove that the te is not null at that position before you complain about the instanceof not working.  Just saying "I'm sure" isn't enough -- print it out right at the point in the code where you are checking it.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

Hi

 

Instance of should work fine for your code.  Your te is almost certainly null.

 

http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom

 

Do you know how to use the debugger?  If not, I reckon you should spend a bit of time learning how, because it'll make your life a whole lot easier, you'll wonder how you ever managed without it.

 

For example

http://www.vogella.com/tutorials/EclipseDebugging/article.html

 

In this case, I'd suggest you put a breakpoint on this line

TileEntity te = world.getTileEntity(x,y-1,z);

 

and it will show you in 30 seconds flat what type of TileEntity you have found (if any).

 

-TGG

 

 

 

 

 

Link to comment
Share on other sites

I put this in my onBlockActivated method:

if(world.getTileEntity(x, y+1, z)!=null)System.out.println("not Null");
if(world.getTileEntity(x, y+1, z) instanceof IPowerContainer)System.out.println("Is Power Container");

 

the block that I placed on top implemented IPowerContainer and had a TileEntity this is what I got in the console:

not Null

 

The proud(ish) developer of Ancients

Link to comment
Share on other sites

We're just saying that it should work.  And when something that should work doesn't work, then it is time to trace things really carefully.  The code you've posted it is not at all obvious that you've confirmed that the te is really what you think it is.  Maybe you did try it, but you haven't shown any proof.

 

Based on the code you listed, there is is only a few possible causes:

1) the class isn't actually an instance of that interface.  Can you post the code for the tile entity class?

2) the tile entity is null.  Again the code you've shown so far would not prevent that case, so it would be good to show proof.

3) there is a tile entity there (not null) but not the one you expect.

 

Maybe you have this last case.

 

As strumshot mentions, another way to confirm whether it is actually an instance is to try to cast it into the interface.  If that fails then it would tell you something.

 

Anyway, debugging isn't about trusting that you know something is correct.  Obviously something you think is correct is actually wrong.  This happens all the time in programming -- every bug is something you think that should work but doesn't.  The only thing to do is to exactly trace everything all at the same time.

 

You can check any source on Java programming and instanceof should work for testing classes that implement an interface, as per the stackoverflow link above also attests.  You can also try the isApplicable() method alternative.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

I know how to use the debugger mode, and I've done System.out.println(te) before and it wasn't null and instanceof wasn't returning true still...

OK.  So what is the reason you haven't added a breakpoint to this line

TileEntity te = world.getTileEntity(x,y-1,z);

and discovered what kind of TileEntity you actually get in te?

 

-TGG

Link to comment
Share on other sites

Did you register your TileEntitiy? Of the Battery and the Cable?

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Slot depo 5k merupakan situs slot depo 5k yang menyediakan slot minimal deposit 5rb atau 5k via dana yang super gacor, dimana para pemain hanya butuh modal depo sebesar 5k untuk bisa bermain di link slot gacor thailand terbaru tahun 2024 yang gampang menang ini.   DAFTAR & LOGIN AKUN PRO SLOT DEPO 5K ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
    • Slot deposit 3000 adalah situs slot deposit 3000 via dana yang super gacor dimana para pemain dijamin garansi wd hari ini juga hanya dengan modal receh berupa deposit sebesar 3000 baik via dana, ovo, gopay maupun linkaja untuk para pemain pengguna e-wallet di seluruh Indonesia.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT 3000 ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
    • OLXTOTO: Menikmati Sensasi Bermain Togel dan Slot dengan Aman dan Mengasyikkan Dunia perjudian daring terus berkembang dengan cepat, dan salah satu situs yang telah menonjol dalam pasar adalah OLXTOTO. Sebagai platform resmi untuk permainan togel dan slot, OLXTOTO telah memenangkan kepercayaan banyak pemain dengan menyediakan pengalaman bermain yang aman, adil, dan mengasyikkan. DAFTAR OLXTOTO DISINI <a href="https://imgbb.com/"><img src="https://i.ibb.co/GnjSVpx/daftar1-480x480.webp" alt="daftar1-480x480" border="0" /></a> Keamanan Sebagai Prioritas Utama Salah satu aspek utama yang membuat OLXTOTO begitu menonjol adalah komitmennya terhadap keamanan pemain. Dengan menggunakan teknologi enkripsi terkini, situs ini memastikan bahwa semua informasi pribadi dan keuangan para pemain tetap aman dan terlindungi dari akses yang tidak sah. Beragam Permainan yang Menarik Di OLXTOTO, pemain dapat menemukan beragam permainan yang menarik untuk dinikmati. Mulai dari permainan klasik seperti togel hingga slot modern dengan fitur-fitur inovatif, ada sesuatu untuk setiap selera dan preferensi. Grafik yang memukau dan efek suara yang mengagumkan menambah keseruan setiap putaran. Peluang Menang yang Tinggi Salah satu hal yang paling menarik bagi para pemain adalah peluang menang yang tinggi yang ditawarkan oleh OLXTOTO. Dengan pembayaran yang adil dan peluang yang setara bagi semua pemain, setiap taruhan memberikan kesempatan nyata untuk memenangkan hadiah besar. Layanan Pelanggan yang Responsif Tim layanan pelanggan OLXTOTO siap membantu para pemain dengan setiap pertanyaan atau masalah yang mereka hadapi. Dengan layanan yang ramah dan responsif, pemain dapat yakin bahwa mereka akan mendapatkan bantuan yang mereka butuhkan dengan cepat dan efisien. Kesimpulan OLXTOTO telah membuktikan dirinya sebagai salah satu situs terbaik untuk penggemar togel dan slot online. Dengan fokus pada keamanan, beragam permainan yang menarik, peluang menang yang tinggi, dan layanan pelanggan yang luar biasa, tidak mengherankan bahwa situs ini telah menjadi pilihan utama bagi banyak pemain. Jadi, jika Anda mencari pengalaman bermain yang aman, adil, dan mengasyikkan, jangan ragu untuk bergabung dengan OLXTOTO hari ini dan rasakan sensasi kemenangan!
    • Slot deposit dana adalah situs slot deposit dana yang juga menerima dari e-wallet lain seperti deposit via dana, ovo, gopay & linkaja terlengkap saat ini, sehingga para pemain yang tidak memiliki rekening bank lokal bisa tetap bermain slot dan terbantu dengan adanya fitur tersebut.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT DANA ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
    • Slot deposit dana adalah situs slot deposit dana minimal 5000 yang dijamin garansi super gacor dan gampang menang, dimana para pemain yang tidak memiliki rekening bank lokal tetap dalam bermain slot dengan melakukan deposit dana serta e-wallet lainnya seperti ovo, gopay maupun linkaja lengkap. Agar para pecinta slot di seluruh Indonesia tetap dapat menikmati permainan tanpa halangan apapun khususnya metode deposit, dimana ketersediaan cara deposit saat ini yang lebih beragam tentunya sangat membantu para pecinta slot.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT DANA ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.