Cast Class to some interface
Suppose, i have an
Object obj;
then i can cast it to any interface an� invoke any instance methods/
but if i have
Class myClass = obj.getClass()...
and i now in advance that this class implements some static method of some interface
how can i cast a Class instance?
something like that
((MyInterface)myClass).some_static_method
???
well, how can i directly invoke static method,
if i use dynamic loading??Dynamic loading is not a good mechanism for bringing in static methods. If the loaded classes are yours and you can still change the design, the "canonical" way would be to make the method non-static and provide a default instance (or even a singleton) in a static variable (presumably in the base class that is not loaded dynamically) that gets initialized when loading the subclass. This works fine if your program uses that one subclass throughout its lifetime and the only reason to load it dynamically was that the reference to the class should not be hardcoded.
If you have several subclasses at the same time, then your problem would be how to know when to call this subclass and when that one. Once you know that, you will also have a way to know which instance to call - assuming that you create an instance of each subclass as it is loaded to provide the non-static method. Maybe you would provide the instances in a HashMap or whatever...
If you use reflection you can also call a static method in a non-hardcoded way. This is more cumbersome to code and perhaps slower in speed. Since you have no instance, you will need to query the class by name (unless you have direct access to the loaded java.lang.Class), i.e. you will have to know its fully qualified classname.
Class myClass = myClassLoader.loadClass("some_class");
then, i know, that this class extends abstract class
with some static methods
and now, i want something like this
((MyAbstractClass)myClass).method1();
of course, i could do the following
Object obj = myClass.newInstance();only if it has a default constructor!
((MyAbstractClass)obj).method1()But this is the same as:
MyAbstractClass.method1();
I.e. you would call the static method in MyAbstractClass, NOT in a (perhaps dynamically loaded) subclass!
This is true because for static methods no dynamic (i.e. runtime) binding takes place.
In other words: There is no true polymorphism for static methods. For polymorphism with dynamic binding you need objects. For static methods you need no objects and never should create objects for invocation because that is not only unnecessary but suggests dynamic binding would occur - which is a wrong suggest.
but i don't want to do so, because i use static methods
only and thus do not need an object to create !!!
is there a method to do soOnly when you know the classname or the java.lang.Class somehow and are using reflection as described in more detail in an earlier message in this thread. Otherwise - i.e. if you need true polymorphism with dynamic binding - you would have to use non-static methods and provide some objects to call the method on them.
Similar Messages
-
Can we type cast class into interface?
Hello all,
Can we type cast class into interface?
If it can ,pls explain me in which suituation can we do?You don't need to explicitly typecast a class to an interface, if the class is implementing the interface.
Example: List list = new ArrayList(); // Cast not required.And search on Google first. I'm sure this question would be answered by the lamest of tutorials. -
Inner classes in my interface - ok, no k, indifferent?
I have an interface and a set of ComparatorS which are only used for objects which implement the interface. So I put the ComparatorS in the interface like so (not actual code because it is for my job):
public interface Abc {
//Class loader should only do this once so they are basically singleton constants
public static final Comparator C_1 = new C1();
public static final Comparator C_2 = new C2();
//... there is one more
public String getSomething();
public String getSomethingElse();
//First Comparator inner class
public class C1 implements Comparator {
private C1(){ }
//implements appropriate methods checking for instanceof Abc in the compareTo method
//Compares something (using getSomething())
/* Second Comparator inner class */
public class C2 implements Comparator {
//same thing
//Compares somethingElse (using getSomethingElse())
} //End interfaceUsage:
Set s = new TreeSet(Abc.C_1);
s.add(abc1);Because the Comparator implementations were specific to objects which implement the interface I felt that was the best way to make that fact clear. If they were over in a separate package it would be confusing that these are for the one interface. If they were in the same package as Abc it wouldn't fit (IMO) because they are more utility type classes.
So it was either that or make them a singleton in their own class files or something like this and I found myself liking this.
Any comments on pros/cons of doing it this way?I'm confused as to why it would make sense to put the
Comparators 'in' the interface but not in the package
with the interface. You can't put them 'in' the
interface without putting them in the package. In
reality, nesting them in the interface just creates
classes in the interface's package.My whole deal is that after talking it out I see that it is bad for reuse to have something which could be so generic residing in a particular interface (and therefore deduced soon after that in the same package as my interface). Which made me decide not to have the inner classes because it IS in the same package at that point. But I am saying that is bad. As I tried to state before, for the same reason I now think it is bad to have the classes in the interface (not much i.e. no reuse outside of the interface) then it is bad to have it in the same package as the interface (unelegant reuse outside of the package). Because if the getSomething() is getName() that could be used as a comparator for many different objects in different packages. I don't want to limit. This stance was a progression, once I decided not in the interface, I then also decided not in the same package.
Java is strongly typed. If the class isn't an
instance of the class you are casting to (in this
case the interface) it doesn't matter if it has a
method with the same signature. The cast will fail.Yes, of course, but like generics, you are not limited to just one type (Object is the type of the parameter). So I can either use instanceof before casting (not the best way) or I could have private overloads of the compareTo() method, a new one for every type I support and each supported type which has a getName() could come from a couple different packages. Not that generics does it the same way but on top of being about to declare hierachies that a genericized object can deal with you can also have comma delimitted other objects. They don't have to be related by package or hierarchy in generics. So I don't think it would be so bad for my Comparator to be (if it fit that these different types all had the same method needed by my Comparator).
>>
Here's anothe reason not to do that. Let's say that
someone is using the interface. They need to compare
it to something else, if the Comparators are right
there with the interface, they will be likely to find
them. If they are in some other package, they'd have
to know where to go look for them.If that is the case, where I was worried about easy to find then I would go back to using inner classes with each Comparator as a constant. If I was worried about ease of finding where these ComparatorS are over code reuse across packages.
I mean, I think if I am going to tie the ComparatorS so close to a particular Type then I am going to add it as an inner class whether my type was an interface or a class. At least that is what I am thinking now.
>
This is what I am talking about. So many Java
developers treat packages like filing cabinets. I
put things that do this here and things that do that
there. But this is actually not very useful and it
hamstrings your designs.
Java doesn't have a friend class syntax like C++. So
there's no way to say this class over here has access
to this but no one else does. These kinds of
relationships are very desireable. Some classes will
need to access things in another class that shouldn't
be public. You can do this cleanly if they ae in the
same package but not otherwise.But I am not talking about taking an abstract class putting it in pack1 an a subclass in pack2. I am talking about putting a utility class that could eventially work on 50 classes in a place that is playingfield neutral and not in the original type it deals with today only. I am dealing with public accessor methods on my objects.
>
For example. Let's say you want to create a Factory
(I'm using Factory in a loose way here not
necessarily a GoF Pattern) for a public class. You
don't want every class to have access to contructor
because it creates the Object without initializing
all the necessary atttributes. The factory is
specially crafted to do this with protected info and
access rights. If you put the class and the factory
together it;s a snap. You create a package-protected
constructor, some package-protected methods and/or
fields and do it. No class outside the package will
be able to do these dangerous operations. How do you
do this if you have a factory package and a data
object package?That is a whole nother situation I think. In that case it is obvious. I thought my situation was a little less obvious because of the utility nature of the classes (ComparatorS) that I was dealing with. -
What is the diff b/w Abstract class and an interface ?
Hey
I am always confused as with this issue : diff b/w Abstract class and an interface ?
Which is more powerful in what situation.
Regards
VinayHi, Don't worry I am teach you
Abstract class and Interface
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Edited by SASIKUMARA
SIT INNOVATIONS- Chennai
Message was edited by:
sasikumara
Message was edited by:
sasikumara -
Class implementation for interface
Hello,
I am a beginner in ABAP Objects.
In the coding of method if_swf_ifs_workitem_exit~event_raised of class CL_SWF_UTL_EXIT_NEW
There is the instruction follow :
*Get the workflow container
irh_container ?= im_workitem_context-> get_wf_container()
Im_workitem_context is interface type "IF_WAPI_WORKITEM_CONTEXT"
If I execute in debug mode I see the implemtation class of this interface (im_workitem_context) is "CL_SWF_RUN_WORKITEM_CONTEXT"
But where this information of implementation is defined ? (I saw nothing)
Regards
Christine
Edited by: chris_75 on Sep 7, 2010 4:22 PMInterfaces allow to implement highly scalable object oriented applications.
Interface is a kind of a template for a real class which forces this class to implement methods defined in an interface.
The main characteristics of an interfaces are:
- they DO NOT contain any implementations (so there is nothing like INTERFACE ... IMPLEMENTATION - they have only DEFINITIONS - implementations are within classes)
- they have only PUBLIC sections.
Why we need an interface. The answer is simple:
We want to handle some objects uniformly from one application compotent, whereas these objects may behave differently inside.
Example:
Let's say we need to build a sorting program for numbers.
The program would have an interface variable L_RIF_SORTER of an interface LIF_SORTER. LIF_SORTER has a method definition SORT with an C_TAB changing parameter.
Sorting application would call the sorting algorithm as follows:
L_RIF_SORTER->SORT( CHANGING c_tab = l_tab ).
Now is the main point:
We want to have 2 kinds of sorting algorithms implemented, let's say BUBBLE SORT and QUICK SORT.
To do so, we implement 2 classes: LCL_BUBBLE_SORT and LCL_QUICK_SORT.
Both classes implement interface using the statment INTERFACES in a public section.
The user would have to choose the algorithm from an input field. Depending on the content of this field the sorting application would instantiate one class or the other using the statement:
CREATE OBJECT l_rif_sorter TYPE (variable_with_class_name).
THis is the point where ABAP gets to know the real object and its type behind the interface.
This approach is generally called the STRATEGY PATTERN. See Wikipedia for this.
I hope I answered your question.
Regards, -
When to use abstract class compared to interface
hi
can some one plase advise me when to use abstract class compared to interface?
Example will be appreciated...So an abstract class can carry implementation. This can be used to formulate a rule of thumb as to when to use it over an interface.
If you have a so called type specialization relationship between the subtypes and the supertype then they're likely to benefit from shared implementation provided by the supertype, so use class (abstract or concrete) extension in this case. Type specialization is when the supertype represents a general concept like Fruit and the subtypes are specialized forms of that like Apple and Banana.
Another common kind of relationship is called type expansion. In this case the subtypes are unlikely to have any use of implementation provided by the supertype, so use interface implementation. Type expansion is when the supertype represents a specific character the subtypes take on. For example Apple and Bicycle ure unrelated in the type specialization sense but still can share a common character like Comparable. The subtypes have been expanded to include the supertype character, namely the ability to be compared. -
Hii people!
I am having the following exception when doing the full deployment in bcc:
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
java.lang.ClassCastException: Unable to cast class atg.repository.content.GroupQueryBuilder to class atg.adpater.gsa.query.Builder. This means that the repository item descriptor 'promotion' in the repository 'ProductCatalog-ver' is transient but was expected to be persistent. This can occur when a repository item is removed or renamed and subsequent layers (e.g. liveconfig or localconfig) continue to reference the old repository item name to define caching configuration. The item becomes transient because the base item descriptordefinition that defines the primary table no longer exists.
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.gsa.GSAItemDescriptor.getBuilder(GSAItemDescriptor.java:10520)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionItemDescriptor.getLineFilter(VersionItemDescriptor.java:3622)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionItemDescriptor.getLineFilter(VersionItemDescriptor.java:3578)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionItemDescriptor.getVersionIDsInLine(VersionItemDescriptor.java:2963)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionRepository.getVersionIDsInLine(VersionRepository.java:6396)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionRepository.getVersionItemsInLine(VersionRepository.java:6260)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionRepository.getVersionItemsInLine(VersionRepository.java:6225)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.adapter.version.VersionRepository.getCurrentVersionItemsInLine(VersionRepository.java:6098)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.versionmanager.impl.DevelopmentLineRepositoryImpl.get(DevelopmentLineRepositoryImpl.java:542)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.versionmanager.impl.DevelopmentLineRepositoryImpl.getCurrentAssetVersions(DevelopmentLineRepositoryImpl.java:319)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.versionmanager.impl.DevelopmentLineRepositoryImpl.getCurrentAssetVersions(DevelopmentLineRepositoryImpl.java:288)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.deployment.server.Deployment.createSourceAssetStates(Deployment.java:5883)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.deployment.server.Deployment.getDeploymentAssetStates(Deployment.java:5826)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.deployment.server.Deployment.getDeploymentMetaData(Deployment.java:2220)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.deployment.server.Deployment.updateStatusWithAffectedDestinations(Deployment.java:2061)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at atg.deployment.server.Deployment.run(Deployment.java:1909)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
at java.lang.Thread.run(Thread.java:662)
**** Error
Ter Nov 19 16:09:05 BRST 2013
1384884545293
/atg/epub/DeploymentServer
If you could help please.
Thanks!The exception is caused because an item descriptor in the repository is "transient",
meaning that it has no primary table. This situation results in the use of a
different QueryBuilder class that isn't compatible with the Builder interface that is
required, which causes the ClassCastException.
Have you modified the promotion item descriptor? -
Shell we make a class as an interface?
shell we make a class as an interface then how ? give me one example
shell we make a class as an interface then how ?What do you mean? Currently something is a class and you want to change that type to an interface?
If so, then as for "shall you," I don't know. That depends on your needs, time, and skill level.
give
me one exampleAssuming you mean what I think you mean, it might be something like this:
// BEFORE
public class Foo {
public void doStuff() { /* do some stuff */ }
Foo foo =new Foo();
foo.doStuff();
// AFTER
public interface Foo {
void doStuff();
public class SimpleFoo implements Foo {
public void doStuff() { /* do some stuff */ }
Foo foo = new SimpleFoo();
foo.doStuff(); -
Some interfaces are not shown in the sxmb_moni
Hi all,
We are facing the following scenario: we have one interface in XG1 (development environment) which is very simple: it consists of a sender File and a receiver IDOC. The file format has been double checked and apparently is what XI defines but when we execute, we can not see anything in the sxmb_moni and if we look into the adapter monitor -> file adapter, we can see that the sender seems to execute successfully but the receiver still shows the following: no message processing until now. So no IDOC is generated and no xml message can be seen in the TCODE sxmb_moni.
Also we have some interfaces that has file receivers and we have the same problems. So, for any reason, the receivers are not working properly. I have refreshed CPACache but the error persists.
It is preventing a whole team of doing some tests and as the golive date (March-April) is approaching it is impacting us in a strong way.
Could you please give us some support?
XIAFUSER is getting locked periodically (i see it in the SLD user management), do you think it will be the main reason of this?
Thanks in advance and kind regardsHi,
Go to Tcode SXI_CACHE for refreshing the Directory Caches. Go to Adapter Engine link and refresh the same
Go thru following threads may be useful.
Message not seen in SXMB_MOni
Missing Messages - in RWB but not sxmb_moni
For Adapter Engine you can do as below.
http://<host>:<port>/CPACache/refresh?mode=full|delta
In addition to above..
Go thru following link about Processed XML messages.
http://help.sap.com/saphelp_nw2004s/helpdata/en/c4/9a5c3bab977239e10000000a114084/frameset.htm
Just add on info.
http://help.sap.com/saphelp_nw2004s/helpdata/en/43/6baeae38391a6ee10000000a11466f/frameset.htm
Hope this helps..
Regards,
Moorthy -
When to use abstract classes instead of interfaces with extension methods in C#?
"Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however,
this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there
is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes
instead of interfaces with extension methods?
A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via
a multitude of extension methods.Hi
Well I believe Interfaces have more uses in software design. You could decouple your component implementing against interfaces so that
you have more flexibility on changing your code with less risk. Like Inversion of Control patterns where you can use interfaces and then when you decide you can change the concrete implementation that you want to use. Or other uses for interfaces is you could
use Interceptors using interfaces (Unity
Interceptor) to do different things where not all of these is feasible or at least as straightforward using abstract classes.
Regards
Aram -
What is actually happenning when we are importing a class of some other pac
Sirs,
I have a doubt which is very basic to java,
I want to import a class say "HashMap" to my class.
If i put import "java.util.HashMap" or "import java.util.*;"
Which will be better ?
If i put "import java.util.*; " will it affect the performance?
What is actually happenning when we are importing a class of some other package to our class
Your help solicited,
Sudheesh K SMany of your questions of this nature can be quickly answered by a search of prior posts to the forums, like this:
http://forum.java.sun.com/thread.jspa?forumID=54&threadID=631979
And why do you tend to post boldened text? It's harder to read. -
To find the implementing classes of an interface
Hi,
Does anyone know a function module or class using which I can find all implementing classes of an interface?
Regards,
SukruHello Sukru
If you are working already on SAP releases >= 6.20 then you will see all implementing classes if you display the interface in SE80 (tree display -> subnode of the interface).
Alternatively, you can call method <b>GET_IMPLEMENTING_CLASSES</b> of class <b>CL_OO_INTERFACE</b> (available on >= 6.40, perhaps on 6.20, too).
Regards
Uwe -
Where are the implementations for some interfaces in the search_sdk.jar?
Hi,
Is the source code for the implementation of some interfaces (DocumentMetadata etc) available to public?
Thanks.
Jun
Message was edited by:
AlwaysthinkSource code is not available. The javadoc is distributed with the installation media. On my machine I can find the javadoc for DocumentMetadata here:
file:///F:/SES_1018_WIN32_DVD2/doc/search.1018/b32260/toc.htm -
Class extends two interface which have method in common name
A class implements two interfaces. Those interfaces have method in common name.
For ex;
public interface b{public void hello();}
public interface c{public void hello();}
public class a implements b,c
public void hello(){}
Since two interfaces have common method, How to differentiate in this case ?How to differentiate what? You have to provide a method called hello(), just as in your example. (Normally you would have code in the method body, but zero lines of code is not against the rules.)
-
I am having trouble sending an audio signal from my computer (mac pro early 2009) to my TV. Is there some interface or adapter that allows /enables the audio input from my computer to be sent to the TV (R,L signal?) any suggestions
just the audio, eh?. If you were using DVI or DisplayPort that might be different, but for audio alone, it shouldn't be that hard. Just grab a 3.5 mm stereo plug to 2 rca cables adapter. Plug the smaller end into the back of your Mac Pro (or the Front), where you see either the headphone or speaker icon). Alt-click on the speaker icon at the top of your screen to show all audio inputs and outputs. Make sure it's set to Line Out. Plug the red and white end into the audio in jacks on the back of your tv and set it to the correct input. I don't know if your tv will allow just the audio to play. Usually one has to connect up something else, but hopefully I'm wrong. If you were using DVI, or DisplayPort, you'd need an active DVI--HDMI adapter or a DisplayPort to HDMI adapter, but
I don't know for sure
J B
Maybe you are looking for
-
Hi Experts, As per my requirment I need fetch two different categories of matnr based on movment type from mseg.. For eg: If I have two itab's : itab1 and itab2. In itab1 the available records are: matnr werks lifnr mat1 unit1 ABC
-
I never updated my iTunes to version 7 and now it says theres an error?
It doesn't recognize my iPod, does that mean I need to get version 7?
-
1.1.3 Mail reporting errors
So ever since upgrading mail's read and unread email ticker has been acting funky. It will display a blue dot on already read messages, the actual number displayed over the icon is always wrong, and it often times will mark some messages unread and n
-
Click on JCheckBox in JTable gets me a NullPointerException
Hi everyone, The subject says almost everything : I have a JTable with one colum with check boxes and another one with combo boxes. When I select a check box the value of the combo box of the same line is updated but for some reason I get the followi
-
Replacing old Time Capsule Drive with New one...how?
I recently purchased a larger hard drive to be my Time Capsule drive because the current drive was getting close to capacity. Is there a way to migrate/copy/clone/move my backup history to this new drive or do I have to start from scratch. If I start