Static functions instantiating objects
I am a beginner in Java. I would like to know
if a static function can instantiate other Java objects?
X and Y are public classes.
class Y has a static method fnStatic()
Can Something like this allowed?
static void fnstatic()
X obj = new X(..);
X. regFn();
Meena
Actually, I have a class Session, which has a method ProcessEvent()
public class Session{
public synchronized void processEvent(Event e)
// Processing of the event
// Generate a response for the Event
This Session class is the mainstream code..
Now I want to write a TestClass that will test the main code.
So I have a Test class as below:
public class Test {
public static void sendReq()
// Construct an event and call processEvent Function from the main code
Event ev = new Event();
// Fill the event with parameters
Session sess = new Session();
sess.processEvent(ev);
What I am thinking of doing is: Call the static method in another class called Manager of the mainstream code for test purpose as follows:
public class Manager {
public void somefunction()
//*** Just for test purpose: do the following line **//
Test.sendReq();
I am not sure what I am trying to do will work. I would appreciate if you can comment on that or suggest something that would work for me.
Another thing which I want to do is:
Inside ProcessEvent(), I want to call another static method ParseandValidateResponse() of the TestClass This looks odd, but as long as it works, it would be fine for me because this is only for test purpose.
In this case, I would write,
public class Session{
public synchronized void processEvent(Event e)
// Processing of the event
// Generate a response for the Event
Test.parseandValidateResponse(Response res);
public class Test {
public static void sendReq()
// AS SHOWN PREVIOUSLY
public static void parseandValidateResponse(Response resp)
// validate the response
}
Similar Messages
-
Can not call a static function with-in a instance of the object.
Another FYI.
I wanted to keep all of the "option" input parameters values for a new object that
i am creating in one place. I thought that the easiest way would be to use a
static function that returns a value; one function for each option value.
I was looking for a way to define "constants" that are not stored in
the persistent data of the object, but could be reference each time
the object is used.
After creating the static functions in both the "type" and "body" components,
I created the method that acutally receives the option input values.
In this method I used a "case" statement. I tested the input parameter
value, which should be one of the option values.
I used a set of "WHEN conditions" that called the same
static functions to get the exact same values that the user should
pass in.
When I try to store this new version, I get the error:
"PLS-00587: a static method cannot be invoked on an instance value"
It points to the first "when statifc_function()" of the case function.
This seems weird!
If I can call the static method from the "type object" without creating
and instance of an object, then why can't I call it within the body
of a method of an instance of the object type?
This doesn't seem appropriate,
unless this implementation of objects is trying to avoid some type
of "recursion"?
If there is some other reason, I can not think of it.
Any ideas?Sorry for the confusion. Here is the simplest example of what
I want to accomplish.
The anonymous block is a testing of the object type, which definition follows.
declare
test audit_info;
begin
test := audit_info(...);
test.testcall( audit_info.t_EMPLOYER() );
end;
-- * ========================================== * --
create or replace type audit_info as object
( seq_key integer
, static function t_EMPLOYER return varchar2
, member procedure test_call(input_type varchar2)
instantiable
final;
create or replace type body audit_info
as
( id audit_info
static function t_EMPLOYER return varchar2
as
begin
return 'EMPLOYER';
end;
member procedure test_call(input_type varchar2)
as
begin
CASE input_type
WHEN t_EMPLOYER()
select * from dual;
WHEN ...
end case;
end;
end;
The error occurs on the "WHEN t_EMPLOYER()" line. This code is only
an example.
Thanks. -
Problem with instantiation in static function
I have a problem with instatiation of objects in a static function. When I do something like this,
public static void test1() {
String s = new String();
everything works fine, but when I try to do the same with a internally defined class, I get the error "non-static variable this cannot be referenced from a static context".
My code looks roughly like this:
public static void test2() {
Edge e = new Edge();
class Edge {
public int y_top;
public double x_int;
public int delta_y;
public double delta_x;
The compiler complains with the mentioned error message over the creation of a new Edge object and I don't have the slightest clue why... :| When I put the class Edge into an external file, it works.
Can anyone help me out there?Your class Edge is a member of the instance of the current class. You don't have an implicit instance of the current class (the "this" reference) in a static context, therefore you get the error.
You need to either declare Edge as static, move it outside your class, or create an explicit instance of the outer class which you use to create instances of Edge ("Edge e = new YourMainClass().new Edge()") -
Need help with usage of static functions
Hi,
I tried instantiating objects within static functions as follows: It gives error:
If someone can explain an alternate way of doing things, I would appreciate:
public class C {
* @param args
public static void main(String[] args) {
Y.Fn1();
public class X {
public void Fn2(){
int b=2;
System.out.println("hello");
public class Y {
public static void Fn1()
int a=2;
X obj = new X();
obj.Fn2();
The actual error is:
Cannot make a static referencxe to the nonstatic method Fn2() from the type X Y.java
Need Help : If someone can comment on the following, I would appreciate:
I have a class Session, which has a method ProcessEvent()
public class Session{
public synchronized void processEvent(Event e)
// Processing of the event
// Generate a response for the Event
This Session class is the mainstream code..
Now I want to write a TestClass that will test the main code.
So I have a Test class as below:
public class Test {
public static void sendReq()
// Construct an event and call processEvent Function from the main code
Event ev = new Event();
// Fill the event with parameters
Session sess = new Session();
sess.processEvent(ev);
What I am thinking of doing is: Call the static method in another class called Manager of the mainstream code for test purpose as follows:
public class Manager {
public void somefunction()
//*** Just for test purpose: do the following line **//
Test.sendReq();
I am not sure what I am trying to do will work. I would appreciate if you can comment on that or suggest something that would work for me.
Another thing which I want to do is:
Inside ProcessEvent(), I want to call another static method ParseandValidateResponse() of the TestClass This looks odd, but as long as it works, it would be fine for me because this is only for test purpose.
In this case, I would write,
public class Session{
public synchronized void processEvent(Event e)
// Processing of the event
// Generate a response for the Event
Test.parseandValidateResponse(Response res);
public class Test {
public static void sendReq()
// AS SHOWN PREVIOUSLY
public static void parseandValidateResponse(Response resp)
// validate the response
}Sorry I thought no one had replied. When I posted here, I missed seeing yr reply. Later just now I saw yr reply It was in the second Page
(Earlier I was looking only in first page by mistake)
Meena -
I working on .net MVC Entity Framework (Code First).
I am not able to get Datacontext in repository classes functions when i call these functions from a static function in controller . I am getting the Exception
"An exception of type 'System.NullReferenceException'
occurred in YYYYYY.Web.dll(Default
project dll) but was not handled in user code
Additional information: Object reference not set to an instance of an object."
i need to call static functions since i had to call some functions asynchronously.Like Report generation
This works perfectly fine when called from a non static function in controller.
Thanks in advance
PunnooseBut when i call a function in repository class, With dependency Injection(NInject).
eg:-
public Batch GetBatchDetail(string batchID)
return this.db.Batches.Where(x => x.ID=batchID).FirstOrDefault();
Db is Datacontext
I am getting the Exception "An exception of type 'System.NullReferenceException'
occurred in YYYYYY.Web.dll(Default
project dll) but was not handled in user code
Please do help me
regards
punnoose -
Member /static function and procedure
hi guys,
i'm trying to figure out diffrerences between the following;
1. member function and static function
2.*member* procdure and static procedure.
i wanna know when to use them when creating an object type.thanks.hope this enlighten you
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/objects.htm#CHDEFBEA -
Cannot call member function on object type
On 8.1.6 I cannot call a member function from SQL in the way described in the manual.
The following example is almost copied from the manual:
create or replace TYPE foo AS OBJECT (a1 NUMBER,
MEMBER FUNCTION getbar RETURN NUMBER);
create or replace type body foo is
MEMBER FUNCTION getbar RETURN NUMBER is
begin
return 45;
end;
end;
CREATE TABLE footab(col foo);
SELECT col,foo.getbar(col) FROM footab; -- OK
select col,col.getbar() from footab; -- ERROR
The second select is the way it should be, but I get an error "invalid column name".
Using the first select, I get the result. This is strange because this is more or less the 'static member' notation (filling in the implicit self parameter myself).
Is this a known bug in 8.1.6, maybe fixed in later versions?Konstantin,
Did you use loadjava to load the compiled class into the Oracle Database?
Regards,
Geoff
Hello!
I need to write a member function for object type with java.
for example:
create type test as object(
id number,
name varchar2(20),
member function hallo return number);
create type body test as
member function hallo return number
as language java
name 'test.hallo() return int;
create table test of test;
My java-file is:
public class test {
public int hallo() {
return 5;
select t.hallo() from test t;
It's does not run. Why?
I get always an error back. Wrong types or numbers of parameters!!
please help me.
thanks in advance
Konstantin -
Is Using Static functions advisable from performance(speed) point of view
I was wondering if using a static function would be slower than using a normal function, especially when the function is to be accessed by multiple threads since the same memory area is used each time the static function is accessed from any of the threads. Thus is it right if I say that static functions are not suitable for multiThreaded access ?
I was wondering if using a static function would be
slower than using a normal function,Static functions are linked at compile time, while normal functions have to be linked based on the runtime type of the object they are called on. This lookup means that static function invocations are likely to be faster.
especially when
the function is to be accessed by multiple threads
since the same memory area is used each time the
static function is accessed from any of the threads.If you are talking about the code segment, where the function definition is held, there is only a single copy of each "normal" function as well. The code segment is also read-only, so there are no issues with multiple threads reading and executing the same code at the same time.
There are the normal issues with multi-threaded access to variables in static functions that exist with normal functions.
Thus is it right if I say that static functions are
not suitable for multiThreaded access ?Static functions are no safer than non-static functions in terms of thread safety. On the other hand, it is no more dangerous having multiple threads calling a static function than having multiple threads calling a non-static function on the same object. Exactly the same thread safety techniques apply whether you are working in a static or a non-static context.
With the above in mind, there is a great deal of design difference between static functions and non-static functions. They mean very different things when creating a system, and an operation that is suited for a static function is very likely not appropriate in a non-static context, and vice versa. The important thing is to make sure the design is appropriate for what the system is trying to do.
The most common use of static functions is for object creation... The Factory design pattern uses static methods to create objects of a given type, the Singleton design pattern uses static methods to allow access to itself. -
Static function behaviour...
what happns when a static function is used from several classes simultaneously,,,,,,...
will it be multithreaded or synchronized or will it become unstablePotentially, just like an object field used in a regular non-synchronized method. Ordinary local variables are fine, though.
Think of static methods and variables as being attached to the Class object instead of an object instance. -
Question about synchronized static function.
Hi, everyone!
The synchronized statement often deals with an object (called monitor).
But a static function can be invoked without an object.
So if a static function is declared as static, what is the function of
static and synchronized here? Which lock it is using?
Can you give me a simple expplanation?
regards,
GeorgeHence try and avoid synchronizing static methods.
Try and use non static method if you are doing
multithreaded programming. That way you can have lockWell, I avoid static methods, not just when doing multithreading, but not for the reason you mention.
objects which allow non interfering methods to be
accessed in parallelThats easy to do with static methods anyway:
class Foo
static Object lock1 = new Object();
static Object lock2 = new Object();
static void method1()
synchronized( lock1 )
static void method2()
synchronized( lock2 )
}Maybe I just missunderstod you... -
Stage.addChild in static function?
In my document class (called "Level") I have a function:
public function doSomething():void {
stage.addChild(some_mc);
In another class I'm trying to call this function with:
Level.doSomething();
but I get this error:
1061: Call to a possibly undefined method doSomething through a reference with static type Class.
if I make the function static I get this error:
1120: Access of undefined property stage.
I'm not sure what to do here. Some help would be appreciated. Thanks.Hello,
@tlhood
This is how you could do that:
package
import flash.display.MovieClip;
public class Level extends MovieClip
public static function doSomething():void
instance.stage.addChild(instance.some_mc);
public function Level()
Level.instance = this;
// instance is class variable
private static var instance:Level = null;
// stage/some_mc are instance variables
private var some_mc:MovieClip = null;
Level.doSometing();
but most probably you would rather use singleton like implementation instead of static access in case you've e.g. single Level object in game:
http://www.squidoo.com/flash-tutorials_as3-singleton-design-pattern
so you would call:
Level.getInstance().doSomething();
or:
// somewhere in code
var level:Level = Level.getInstance();
// sometimes later in some other part of code
level.doSomething();
regards,
Peter -
Is Static Function faster than non-static function
Hi,
I am wondering the performances issues of static Vs non-static function.
To prevent object creation, I wrote some static function in my class but I wonder if it really did faster.
any pointers in this direction will be helpful
Jacinleto mattbunch
I still haven't pinpointed exactly the system
bottleneck
but I do think finding a better approach at the
earliest time is betterActually, the generally accepted best practice is to start with good algorithms and data structures, write the code, test the code, profile the code, and then do this kind of nickel and dime optimization after specific bottlenecks have been pinpointed. You absolultely should not make a static/non-static decision based on performance considerations. In fact, the idea that non-static is slower due to object creation is rather muddy thinking. You'd either already have the object and invoke its non-static method, or you'd invoke a static method. In the static case, your design would probably be different anyway, so you can't predict whether time saved by not creating an object would be lost by executing other code paths.
The case in which you count object creation time is if you're creating an object just to call this one method on it and get that method's result, and then not using the object anymore. In that case, the method should be static--not for performance reasons, but rather because the way you are using it suggests that the appropriate design is for it to be static.
>
so many decision to be made in designing software
I wonder if there is any practise I can follow
See "Thinking in Java" by Bruce Eckel, and "Practical Programming in Java" by Peter Haggar -
Hi,
Could somebody tell me if i can embed a static function (ABAP) in an XSLT.
Thanks in advance
RachanaHi,
Thanks a lot and this should help me. But I'm not that well-versed in XSLT.
Hence,
I'm getting an xml namespace not defined error now.
my XSLT looks like this
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="no"/>
<xsl:template match="TaskType">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<TASKTYPEDESIGN>
<SBTM_CR_TT_DESIGN>
<ORIGINAL_LANG>
<xsl:value-of select="../@origLang"/>
</ORIGINAL_LANG>
<sap:call-external class="CL_SBTM_XML_CONVERSION" method="GET_SYLANGU">
<sap:callvalue param="EXTERNAL" select="../@language"/>
<sap:callvariable param="INTERNAL" name="SY_LANG"/>
</sap:call-external>
</SBTM_CR_TT_DESIGN>
</TASKTYPEDESIGN>
</asx:values>
</asx:abap>
</xsl:template>
I tried to fit in that code there...but i guess this is not the way.
please help -
Abstract class and static function
Please tell me that why a static function can't be made abstract?
Thanks.
Edited by: RohitRawat on Sep 9, 2009 7:45 AMRohitRawat wrote:
Please tell me that why a static function can't be made abstract?
Thanks.Because the method belongs to the class. -
Problem in getting the function template object from the repository.
Hi all,
I have created a par file. I have a JCO connection in that. I am facing problems in getting the function template object from the repository. This thing is running successfully when i try to deploy it in Tomcat. But i am facing problems when i try to deploy it in SAP EP 6.0.
Below is statement which is giving error after being deployed to SAP EP6.
This is executing fine when executed in Tomcat Server.
// getting the object of function template
IFunctionTemplate functionTemplate =
aRepository.getFunctionTemplate("YADDNEWUSER");
Note : YADDNEWUSER is the name of the RFC which I am calling from my JAVA Code.
Thanks in advance,
DivijaThis sounds like a bug in the smart upload code. I have used this stuff before, but it's probably an older version, so maybe they broke something. Enumerations aren't usually guaranteed to keep things in any particular order. I would say for now, make a method to take the enumeration and a param name to find the value. And write to the JSPSmart people.
Maybe you are looking for
-
Any stock broker/mutual fund traders using a Mac?? I need your help!
Hi there. I am a recent switcher and love my Mac so much I want to get a friend to switch as well. He is stuck on Windows 98 (and all of the problems that come with it) since he is running an old stock trader client database called MarketMate. It too
-
Trying to install new hard drive in MacBook
Hello, I am at a dead end and would appreciate your help. Due to a no-boot situation that I chased for several days. My hard drive was damaged (many corrupt/damaged/orphaned files) I confirmed that by using Apple Hardware test and then running a fsca
-
How to solve error essbase encoding ?
Dear All, Today, I just wanted to load data into a demo database, however, I found that the load information of data load results is error encoding as below: ÕýÔÚ¶ÁÈ¡Êý¾Ý¿â [Demo] µÄ¹æÔò SQL ÐÅÏ¢ ÕýÔÚ¶ÁÈ¡À´×ÔÊý¾Ý¿â [PLP] ¹æÔò¶ÔÏóµÄ¹æÔò ÆôÓÃÁ˲¢ÐÐÊý¾Ý
-
Black and white photo prints with purple cast
I used Photoshop to convert the digital photos to black and white before placing them in Indesign CS3. On the monitor the photo looks great, but when I print the newsletter, each photo has a purple tint. What am I doing wrong? Thanks.
-
Hi everyone, Is there any way to receive emails directly into the database using apex? Thank you, Alex.