PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 13, 2022

[FIXED] How do I call a non-static method from inside a static method?

 November 13, 2022     cookies, memcached, non-static, spring-mvc, static     No comments   

Issue

I have a utility Cookie class. Which has a getCookie() , trying to call a writetoCache() inside a service implementation class. But inside getCookie(), the writetoCache() is not being recognized.

This is the getCookie().

public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String mse){
//String value = null;
Cookie[] cookies = request.getCookies();
if(cookies != null){
    for(Cookie cookie : cookies){
        if(cookie.getName().equals(name)){
            System.out.println(cookie.getValue());
            System.out.println(cookie.getName());
            System.out.println(cookie.getMaxAge());
            writeToCache(cookie.getName(),cookie.getValue(), 300 );
            return cookie.getValue();
        }
    }
}
return null;
 }

This is the writetoCache() inside memcached service class. I am using memcached - import net.spy.memcached.MemcachedClient;

@Override
public void writeToCache(String key, String value, int expiry) {    
    c.set(key, expiry, value);  
}

One-way is to create the instance of the non-static method's class in static method's class. But it does not work as there is type mismatch.


Solution

If your getCookie is inside the Cookie util, than you're not calling the writeToCache on memcache client instance rather as s method of Cookie. So something's not right there, double check it.

In any case, don't create a new instance, make your memcache client a singleton:

private static MemCachedClient mcc = new MemCachedClient("foo");

than call the method against the instance:

mcc.writeToCache(cookie.getName(),cookie.getValue(), 300 );


Answered By - Master Slave
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing